Upgrade to 2021 Rust edition

- set 1.62 Rust as MSRV
- use new fmt syntax where possible
- refactor `.to_owned()`, `.to_string()` and `.into()` usage
- rename `IntoResolvable::into()` as `IntoResolvable::into_resolvable()` to disambiguate with `Into::into()`
- use `#[derive(Default)]` for enums where possible
- use `bool::then_some()` where possible
This commit is contained in:
tyranron 2022-07-13 12:30:51 +02:00
parent 9e87a11071
commit ef7a7e8229
No known key found for this signature in database
GPG key ID: 762E144FB230A4F0
183 changed files with 1629 additions and 1863 deletions

View file

@ -1,7 +1,7 @@
[package] [package]
name = "juniper_benchmarks" name = "juniper_benchmarks"
version = "0.0.0" version = "0.0.0"
edition = "2018" edition = "2021"
authors = ["Christoph Herzog <chris@theduke.at>"] authors = ["Christoph Herzog <chris@theduke.at>"]
publish = false publish = false

View file

@ -38,7 +38,7 @@ fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) {
b.iter(|| { b.iter(|| {
j::execute_sync( j::execute_sync(
SYNC_QUERY, 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(|| { b.iter(|| {
let f = j::execute( let f = j::execute(
ASYNC_QUERY, ASYNC_QUERY,
vec![("ids".to_string(), ids.clone())].into_iter().collect(), vec![("ids".to_owned(), ids.clone())].into_iter().collect(),
); );
rt.block_on(f) rt.block_on(f)
}) })
@ -77,7 +77,7 @@ fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) {
b.iter(|| { b.iter(|| {
let f = j::execute( let f = j::execute(
ASYNC_QUERY, ASYNC_QUERY,
vec![("ids".to_string(), ids.clone())].into_iter().collect(), vec![("ids".to_owned(), ids.clone())].into_iter().collect(),
); );
rt.block_on(f) rt.block_on(f)
}) })

View file

@ -11,11 +11,11 @@ pub type QueryResult = Result<
String, String,
>; >;
pub struct Context {} pub struct Context;
impl Context { impl Context {
fn new() -> Self { fn new() -> Self {
Self {} Self
} }
} }
@ -51,8 +51,8 @@ impl User {
Self { Self {
id, id,
kind: UserKind::Admin, kind: UserKind::Admin,
username: "userx".to_string(), username: "userx".into(),
email: "userx@domain.com".to_string(), email: "userx@domain.com".into(),
gender: Some(Gender::Female), gender: Some(Gender::Female),
} }
} }
@ -97,7 +97,7 @@ pub fn new_schema() -> RootNode<'static, Query, EmptyMutation<Context>, EmptySub
pub fn execute_sync(query: &str, vars: Variables) -> QueryResult { pub fn execute_sync(query: &str, vars: Variables) -> QueryResult {
let root = new_schema(); let root = new_schema();
let ctx = Context::new(); 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 { 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(); let ctx = Context::new();
juniper::execute(query, None, &root, &vars, &ctx) juniper::execute(query, None, &root, &vars, &ctx)
.await .await
.map_err(|e| format!("{:?}", e)) .map_err(|e| format!("{e:?}"))
} }

View file

@ -13,4 +13,4 @@ create-missing = false
git_repository_url = "https://github.com/graphql-rs/juniper" git_repository_url = "https://github.com/graphql-rs/juniper"
[rust] [rust]
edition = "2018" edition = "2021"

View file

@ -68,7 +68,7 @@ use std::env;
pub fn get_db_conn() -> Connection { pub fn get_db_conn() -> Connection {
let pg_connection_string = env::var("DATABASE_URI").expect("need a db uri"); 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(); let conn = Connection::connect(&pg_connection_string[..], TlsMode::None).unwrap();
println!("Connection is fine"); println!("Connection is fine");
conn conn
@ -101,7 +101,7 @@ impl BatchFn<i32, Cult> for CultBatcher {
// A hashmap is used, as we need to return an array which maps each original key to a Cult. // 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<i32, Cult> { async fn load(&self, keys: &[i32]) -> HashMap<i32, Cult> {
println!("load cult batch {:?}", keys); println!("load cult batch {keys:?}");
let mut cult_hashmap = HashMap::new(); let mut cult_hashmap = HashMap::new();
get_cult_by_ids(&mut cult_hashmap, keys.to_vec()); get_cult_by_ids(&mut cult_hashmap, keys.to_vec());
cult_hashmap cult_hashmap

View file

@ -66,7 +66,7 @@ type Schema = juniper::RootNode<
fn main() { fn main() {
// Create a context object. // Create a context object.
let ctx = Context{}; let ctx = Context;
// Run the built-in introspection query. // Run the built-in introspection query.
let (res, _errors) = juniper::introspect( let (res, _errors) = juniper::introspect(

View file

@ -98,7 +98,7 @@ where [`Connection`][Connection] is a `Stream` of values returned by the operati
# #
# impl Database { # impl Database {
# fn new() -> Self { # 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<Database>, Subscription>; type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
fn schema() -> Schema { fn schema() -> Schema {
Schema::new(Query {}, EmptyMutation::new(), Subscription {}) Schema::new(Query, EmptyMutation::new(), Subscription)
} }
async fn run_subscription() { async fn run_subscription() {

View file

@ -130,7 +130,7 @@ impl Mutation {
type Schema = juniper::RootNode<'static, Query, Mutation, EmptySubscription<Context>>; type Schema = juniper::RootNode<'static, Query, Mutation, EmptySubscription<Context>>;
# #
# fn main() { # fn main() {
# let _ = Schema::new(Query, Mutation{}, EmptySubscription::new()); # let _ = Schema::new(Query, Mutation, EmptySubscription::new());
# } # }
``` ```

View file

@ -50,7 +50,7 @@ struct Root;
#[juniper::graphql_object] #[juniper::graphql_object]
impl Root { impl Root {
fn foo() -> String { fn foo() -> String {
"Bar".to_owned() "Bar".into()
} }
} }

View file

@ -227,7 +227,7 @@ impl ObjA {
// ^^ the evaluated program panicked at // ^^ the evaluated program panicked at
// 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` // '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.' // 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")
} }
} }

View file

@ -157,7 +157,7 @@ They can have custom descriptions and default values.
# extern crate juniper; # extern crate juniper;
# use juniper::graphql_object; # use juniper::graphql_object;
# #
struct Person {} struct Person;
#[graphql_object] #[graphql_object]
impl Person { impl Person {
@ -177,7 +177,7 @@ impl Person {
#[graphql(default)] #[graphql(default)]
arg2: i32, arg2: i32,
) -> String { ) -> String {
format!("{} {}", arg1, arg2) format!("{arg1} {arg2}")
} }
} }
# #

View file

@ -242,15 +242,15 @@ impl Mutation {
if !(10 <= name.len() && name.len() <= 100) { if !(10 <= name.len() && name.len() <= 100) {
errors.push(ValidationError { errors.push(ValidationError {
field: "name".to_string(), field: "name".into(),
message: "between 10 and 100".to_string() message: "between 10 and 100".into(),
}); });
} }
if !(1 <= quantity && quantity <= 10) { if !(1 <= quantity && quantity <= 10) {
errors.push(ValidationError { errors.push(ValidationError {
field: "quantity".to_string(), field: "quantity".into(),
message: "between 1 and 10".to_string() message: "between 1 and 10".into(),
}); });
} }
@ -338,11 +338,11 @@ impl Mutation {
}; };
if !(10 <= name.len() && name.len() <= 100) { 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) { 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() { if error.name.is_none() && error.quantity.is_none() {
@ -436,11 +436,11 @@ impl Mutation {
}; };
if !(10 <= name.len() && name.len() <= 100) { 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) { 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() { if error.name.is_none() && error.quantity.is_none() {

View file

@ -145,14 +145,13 @@ impl UserId {
S: ScalarValue S: ScalarValue
{ {
input.as_string_value() input.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", input)) .ok_or_else(|| format!("Expected `String`, found: {input}"))
.and_then(|str| { .and_then(|str| {
str.strip_prefix("id: ") str.strip_prefix("id: ")
.ok_or_else(|| { .ok_or_else(|| {
format!( format!(
"Expected `UserId` to begin with `id: `, \ "Expected `UserId` to begin with `id: `, \
found: {}", found: {input}",
input,
) )
}) })
}) })
@ -190,7 +189,7 @@ where
S: ScalarValue S: ScalarValue
{ {
match v { match v {
StringOrInt::String(str) => Value::scalar(str.to_owned()), StringOrInt::String(s) => Value::scalar(s.to_owned()),
StringOrInt::Int(i) => Value::scalar(*i), StringOrInt::Int(i) => Value::scalar(*i),
} }
} }
@ -200,9 +199,9 @@ where
S: ScalarValue S: ScalarValue
{ {
v.as_string_value() 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))) .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<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> { fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
@ -240,7 +239,7 @@ enum StringOrInt {
impl StringOrInt { impl StringOrInt {
fn to_output<S: ScalarValue>(&self) -> Value<S> { fn to_output<S: ScalarValue>(&self) -> Value<S> {
match self { match self {
Self::String(str) => Value::scalar(str.to_owned()), Self::String(s) => Value::scalar(s.to_owned()),
Self::Int(i) => Value::scalar(*i), Self::Int(i) => Value::scalar(*i),
} }
} }
@ -250,9 +249,9 @@ impl StringOrInt {
S: ScalarValue, S: ScalarValue,
{ {
v.as_string_value() 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)) .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<S>(value: ScalarToken<'_>) -> ParseScalarResult<S> fn parse_token<S>(value: ScalarToken<'_>) -> ParseScalarResult<S>
@ -290,7 +289,7 @@ mod string_or_int {
S: ScalarValue, S: ScalarValue,
{ {
match v { match v {
StringOrInt::String(str) => Value::scalar(str.to_owned()), StringOrInt::String(s) => Value::scalar(s.to_owned()),
StringOrInt::Int(i) => Value::scalar(*i), StringOrInt::Int(i) => Value::scalar(*i),
} }
} }
@ -300,9 +299,9 @@ mod string_or_int {
S: ScalarValue, S: ScalarValue,
{ {
v.as_string_value() 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)) .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<S>(value: ScalarToken<'_>) -> ParseScalarResult<S> pub(super) fn parse_token<S>(value: ScalarToken<'_>) -> ParseScalarResult<S>
@ -335,7 +334,7 @@ impl StringOrInt {
S: ScalarValue, S: ScalarValue,
{ {
match self { match self {
Self::String(str) => Value::scalar(str.to_owned()), Self::String(s) => Value::scalar(s.to_owned()),
Self::Int(i) => Value::scalar(*i), Self::Int(i) => Value::scalar(*i),
} }
} }
@ -345,9 +344,9 @@ impl StringOrInt {
S: ScalarValue, S: ScalarValue,
{ {
v.as_string_value() 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)) .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<CustomScalarValue>) -> Result<Date, String> { pub(super) fn from_input(v: &InputValue<CustomScalarValue>) -> Result<Date, String> {
v.as_string_value() 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 `Date`: {}", e))) .and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {e}")))
} }
} }
# #

View file

@ -1,7 +1,7 @@
[package] [package]
name = "juniper_book_tests" name = "juniper_book_tests"
version = "0.0.0" version = "0.0.0"
edition = "2018" edition = "2021"
authors = ["Magnus Hallin <mhallin@fastmail.com>"] authors = ["Magnus Hallin <mhallin@fastmail.com>"]
publish = false publish = false

View file

@ -1,7 +1,8 @@
[package] [package]
name = "example_actix_subscriptions" name = "example_actix_subscriptions"
version = "0.0.0" version = "0.0.0"
edition = "2018" edition = "2021"
rust-version = "1.62"
authors = ["Mihai Dinculescu <mihai.dinculescu@outlook.com>"] authors = ["Mihai Dinculescu <mihai.dinculescu@outlook.com>"]
publish = false publish = false

View file

@ -9,9 +9,9 @@ use actix_web::{
}; };
use juniper::{ use juniper::{
graphql_object, graphql_subscription, graphql_value, graphql_subscription, graphql_value,
tests::fixtures::starwars::schema::{Database, Query}, 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_actix::{graphql_handler, playground_handler, subscriptions::subscriptions_handler};
use juniper_graphql_ws::ConnectionConfig; use juniper_graphql_ws::ConnectionConfig;
@ -37,23 +37,12 @@ async fn graphql(
struct Subscription; struct Subscription;
#[derive(GraphQLObject)]
struct RandomHuman { struct RandomHuman {
id: String, id: String,
name: 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 = type RandomHumanStream =
Pin<Box<dyn futures::Stream<Item = Result<RandomHuman, FieldError>> + Send>>; Pin<Box<dyn futures::Stream<Item = Result<RandomHuman, FieldError>> + Send>>;
@ -84,8 +73,8 @@ impl Subscription {
let human = context.get_human(&random_id).unwrap().clone(); let human = context.get_human(&random_id).unwrap().clone();
yield Ok(RandomHuman { yield Ok(RandomHuman {
id: human.id().to_owned(), id: human.id().into(),
name: human.name().unwrap().to_owned(), name: human.name().unwrap().into(),
}) })
} }
} }
@ -142,7 +131,7 @@ async fn main() -> std::io::Result<()> {
.finish() .finish()
})) }))
}) })
.bind(format!("{}:{}", "127.0.0.1", 8080))? .bind("127.0.0.1:8080")?
.run() .run()
.await .await
} }

View file

@ -1,7 +1,8 @@
[package] [package]
name = "example_basic_subscriptions" name = "example_basic_subscriptions"
version = "0.0.0" version = "0.0.0"
edition = "2018" edition = "2021"
rust-version = "1.62"
authors = ["Jordao Rosario <jordao.rosario01@gmail.com>"] authors = ["Jordao Rosario <jordao.rosario01@gmail.com>"]
publish = false publish = false

View file

@ -16,7 +16,7 @@ impl juniper::Context for Database {}
impl Database { impl Database {
fn new() -> Self { fn new() -> Self {
Self {} Self
} }
} }
@ -45,7 +45,7 @@ impl Subscription {
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>; type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
fn schema() -> Schema { fn schema() -> Schema {
Schema::new(Query {}, EmptyMutation::new(), Subscription {}) Schema::new(Query, EmptyMutation::new(), Subscription)
} }
#[tokio::main] #[tokio::main]

View file

@ -1,7 +1,8 @@
[package] [package]
name = "example_warp_async" name = "example_warp_async"
version = "0.0.0" version = "0.0.0"
edition = "2018" edition = "2021"
rust-version = "1.62"
authors = ["Christoph Herzog <chris@theduke.at>"] authors = ["Christoph Herzog <chris@theduke.at>"]
publish = false publish = false

View file

@ -1,7 +1,8 @@
[package] [package]
name = "example_warp_subscriptions" name = "example_warp_subscriptions"
version = "0.0.0" version = "0.0.0"
edition = "2018" edition = "2021"
rust-version = "1.62"
publish = false publish = false
[dependencies] [dependencies]

View file

@ -12,7 +12,7 @@ use juniper_warp::{playground_filter, subscriptions::serve_graphql_ws};
use warp::{http::Response, Filter}; use warp::{http::Response, Filter};
#[derive(Clone)] #[derive(Clone)]
struct Context {} struct Context;
impl juniper::Context for Context {} impl juniper::Context for Context {}
@ -123,7 +123,7 @@ impl Subscription {
yield Ok(User { yield Ok(User {
id: counter, id: counter,
kind: UserKind::Admin, 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(|| { let homepage = warp::path::end().map(|| {
Response::builder() Response::builder()
.header("content-type", "text/html") .header("content-type", "text/html")
.body("<html><h1>juniper_subscriptions demo</h1><div>visit <a href=\"/playground\">graphql playground</a></html>".to_string()) .body("<html><h1>juniper_subscriptions demo</h1><div>visit <a href=\"/playground\">graphql playground</a></html>")
}); });
let qm_schema = schema(); 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 qm_graphql_filter = juniper_warp::make_graphql_filter(qm_schema, qm_state.boxed());
let root_node = Arc::new(schema()); let root_node = Arc::new(schema());
@ -165,10 +165,10 @@ async fn main() {
.map(move |ws: warp::ws::Ws| { .map(move |ws: warp::ws::Ws| {
let root_node = root_node.clone(); let root_node = root_node.clone();
ws.on_upgrade(move |websocket| async move { 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| { .map(|r| {
if let Err(e) = r { if let Err(e) = r {
println!("Websocket error: {}", e); println!("Websocket error: {e}");
} }
}) })
.await .await

View file

@ -1,7 +1,8 @@
[package] [package]
name = "juniper" name = "juniper"
version = "0.16.0-dev" version = "0.16.0-dev"
edition = "2018" edition = "2021"
rust-version = "1.62"
description = "GraphQL server library." description = "GraphQL server library."
license = "BSD-2-Clause" license = "BSD-2-Clause"
authors = [ authors = [

View file

@ -224,10 +224,10 @@ impl<'a> Type<'a> {
impl<'a> fmt::Display for Type<'a> { impl<'a> fmt::Display for Type<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Self::Named(n) => write!(f, "{}", n), Self::Named(n) => write!(f, "{n}"),
Self::NonNullNamed(n) => write!(f, "{}!", n), Self::NonNullNamed(n) => write!(f, "{n}!"),
Self::List(t, _) => write!(f, "[{}]", t), Self::List(t, _) => write!(f, "[{t}]"),
Self::NonNullList(t, _) => write!(f, "[{}]!", t), Self::NonNullList(t, _) => write!(f, "[{t}]!"),
} }
} }
} }
@ -248,12 +248,12 @@ impl<S> InputValue<S> {
/// Construct an enum value. /// Construct an enum value.
pub fn enum_value<T: AsRef<str>>(s: T) -> Self { pub fn enum_value<T: AsRef<str>>(s: T) -> Self {
Self::Enum(s.as_ref().to_owned()) Self::Enum(s.as_ref().into())
} }
/// Construct a variable value. /// Construct a variable value.
pub fn variable<T: AsRef<str>>(v: T) -> Self { pub fn variable<T: AsRef<str>>(v: T) -> Self {
Self::Variable(v.as_ref().to_owned()) Self::Variable(v.as_ref().into())
} }
/// Construct a [`Spanning::unlocated`] list. /// Construct a [`Spanning::unlocated`] list.
@ -282,7 +282,7 @@ impl<S> InputValue<S> {
o.into_iter() o.into_iter()
.map(|(k, v)| { .map(|(k, v)| {
( (
Spanning::unlocated(k.as_ref().to_owned()), Spanning::unlocated(k.as_ref().into()),
Spanning::unlocated(v), Spanning::unlocated(v),
) )
}) })
@ -467,13 +467,13 @@ impl<S: ScalarValue> fmt::Display for InputValue<S> {
Self::Null => write!(f, "null"), Self::Null => write!(f, "null"),
Self::Scalar(s) => { Self::Scalar(s) => {
if let Some(s) = s.as_str() { if let Some(s) = s.as_str() {
write!(f, "\"{}\"", s) write!(f, "\"{s}\"")
} else { } else {
write!(f, "{}", s) write!(f, "{s}")
} }
} }
Self::Enum(v) => write!(f, "{}", v), Self::Enum(v) => write!(f, "{v}"),
Self::Variable(v) => write!(f, "${}", v), Self::Variable(v) => write!(f, "${v}"),
Self::List(v) => { Self::List(v) => {
write!(f, "[")?; write!(f, "[")?;
for (i, spanning) in v.iter().enumerate() { for (i, spanning) in v.iter().enumerate() {
@ -588,30 +588,30 @@ mod tests {
#[test] #[test]
fn test_input_value_fmt() { fn test_input_value_fmt() {
let value: InputValue = graphql_input_value!(null); 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); 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); 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"); 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); 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); 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); 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]); 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}); 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}");
} }
} }

View file

@ -112,12 +112,11 @@ pub struct LookAheadSelection<'a, S: 'a> {
pub(super) children: Vec<ChildSelection<'a, S>>, pub(super) children: Vec<ChildSelection<'a, S>>,
} }
impl<'a, S> Default for LookAheadSelection<'a, S> // Implemented manually to omit redundant `S: Default` trait bound, imposed by
where // `#[derive(Default)]`.
S: ScalarValue, impl<'a, S: 'a> Default for LookAheadSelection<'a, S> {
{
fn default() -> Self { fn default() -> Self {
LookAheadSelection { Self {
name: "", name: "",
alias: None, alias: None,
arguments: vec![], arguments: vec![],

View file

@ -304,7 +304,7 @@ where
type Type; type Type;
#[doc(hidden)] #[doc(hidden)]
fn into(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S>; fn into_resolvable(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S>;
} }
impl<'a, S, T, C> IntoResolvable<'a, S, T, C> for T impl<'a, S, T, C> IntoResolvable<'a, S, T, C> for T
@ -315,7 +315,7 @@ where
{ {
type Type = T; type Type = T;
fn into(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> { fn into_resolvable(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> {
Ok(Some((FromContext::from(ctx), self))) Ok(Some((FromContext::from(ctx), self)))
} }
} }
@ -328,7 +328,7 @@ where
{ {
type Type = T; type Type = T;
fn into(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> { fn into_resolvable(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> {
self.map(|v: T| Some((<T::Context as FromContext<C>>::from(ctx), v))) self.map(|v: T| Some((<T::Context as FromContext<C>>::from(ctx), v)))
.map_err(IntoFieldError::into_field_error) .map_err(IntoFieldError::into_field_error)
} }
@ -341,7 +341,7 @@ where
{ {
type Type = T; type Type = T;
fn into(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> { fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> {
Ok(Some(self)) Ok(Some(self))
} }
} }
@ -354,7 +354,7 @@ where
type Type = T; type Type = T;
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
fn into(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, Option<T>)>, S> { fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, Option<T>)>, S> {
Ok(self.map(|(ctx, v)| (ctx, Some(v)))) Ok(self.map(|(ctx, v)| (ctx, Some(v))))
} }
} }
@ -367,7 +367,7 @@ where
{ {
type Type = T; type Type = T;
fn into(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S2> { fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S2> {
self.map(Some).map_err(FieldError::map_scalar_value) self.map(Some).map_err(FieldError::map_scalar_value)
} }
} }
@ -382,7 +382,7 @@ where
type Type = T; type Type = T;
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
fn into(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, Option<T>)>, S2> { fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, Option<T>)>, S2> {
self.map(|o| o.map(|(ctx, v)| (ctx, Some(v)))) self.map(|o| o.map(|(ctx, v)| (ctx, Some(v))))
.map_err(FieldError::map_scalar_value) .map_err(FieldError::map_scalar_value)
} }
@ -774,7 +774,7 @@ impl<'a> FieldPath<'a> {
FieldPath::Root(_) => (), FieldPath::Root(_) => (),
FieldPath::Field(name, _, parent) => { FieldPath::Field(name, _, parent) => {
parent.construct_path(acc); parent.construct_path(acc);
acc.push((*name).to_owned()); acc.push((*name).into());
} }
} }
} }
@ -791,7 +791,7 @@ impl<S> ExecutionError<S> {
pub fn new(location: SourcePosition, path: &[&str], error: FieldError<S>) -> ExecutionError<S> { pub fn new(location: SourcePosition, path: &[&str], error: FieldError<S>) -> ExecutionError<S> {
ExecutionError { ExecutionError {
location, location,
path: path.iter().map(|s| (*s).to_owned()).collect(), path: path.iter().map(|s| (*s).into()).collect(),
error, error,
} }
} }
@ -842,10 +842,10 @@ where
defs.item defs.item
.items .items
.iter() .iter()
.filter_map(|&(ref name, ref def)| { .filter_map(|(name, def)| {
def.default_value def.default_value
.as_ref() .as_ref()
.map(|i| (name.item.to_owned(), i.item.clone())) .map(|i| (name.item.into(), i.item.clone()))
}) })
.collect::<HashMap<String, InputValue<S>>>() .collect::<HashMap<String, InputValue<S>>>()
}); });
@ -943,7 +943,7 @@ where
.filter_map(|&(ref name, ref def)| { .filter_map(|&(ref name, ref def)| {
def.default_value def.default_value
.as_ref() .as_ref()
.map(|i| (name.item.to_owned(), i.item.clone())) .map(|i| (name.item.into(), i.item.clone()))
}) })
.collect::<HashMap<String, InputValue<S>>>() .collect::<HashMap<String, InputValue<S>>>()
}); });
@ -1090,7 +1090,7 @@ where
.filter_map(|&(ref name, ref def)| { .filter_map(|&(ref name, ref def)| {
def.default_value def.default_value
.as_ref() .as_ref()
.map(|i| (name.item.to_owned(), i.item.clone())) .map(|i| (name.item.into(), i.item.clone()))
}) })
.collect::<HashMap<String, InputValue<S>>>() .collect::<HashMap<String, InputValue<S>>>()
}); });
@ -1172,7 +1172,7 @@ impl<'r, S: 'r> Registry<'r, S> {
if !self.types.contains_key(name) { if !self.types.contains_key(name) {
self.insert_placeholder( self.insert_placeholder(
validated_name.clone(), validated_name.clone(),
Type::NonNullNamed(Cow::Owned(name.to_string())), Type::NonNullNamed(Cow::Owned(name.into())),
); );
let meta = T::meta(info, self); let meta = T::meta(info, self);
self.types.insert(validated_name, meta); self.types.insert(validated_name, meta);
@ -1209,7 +1209,7 @@ impl<'r, S: 'r> Registry<'r, S> {
S: ScalarValue, S: ScalarValue,
{ {
Field { Field {
name: smartstring::SmartString::from(name), name: name.into(),
description: None, description: None,
arguments: None, arguments: None,
field_type: self.get_type::<I>(info), field_type: self.get_type::<I>(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()`"); let name = T::name(info).expect("Scalar types must be named. Implement `name()`");
ScalarMeta::new::<T>(Cow::Owned(name.to_string())) ScalarMeta::new::<T>(Cow::Owned(name.into()))
} }
/// Creates a [`ListMeta`] type. /// Creates a [`ListMeta`] type.
@ -1299,7 +1299,7 @@ impl<'r, S: 'r> Registry<'r, S> {
let mut v = fields.to_vec(); let mut v = fields.to_vec();
v.push(self.field::<String>("__typename", &())); v.push(self.field::<String>("__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`. /// 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()`"); let name = T::name(info).expect("Enum types must be named. Implement `name()`");
EnumMeta::new::<T>(Cow::Owned(name.to_string()), values) EnumMeta::new::<T>(Cow::Owned(name.into()), values)
} }
/// Creates an [`InterfaceMeta`] type with the given `fields`. /// 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(); let mut v = fields.to_vec();
v.push(self.field::<String>("__typename", &())); v.push(self.field::<String>("__typename", &()));
InterfaceMeta::new(Cow::Owned(name.to_string()), &v) InterfaceMeta::new(Cow::Owned(name.into()), &v)
} }
/// Creates an [`UnionMeta`] type of the given `types`. /// 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()"); 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`. /// 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()"); let name = T::name(info).expect("Input object types must be named. Implement name()");
InputObjectMeta::new::<T>(Cow::Owned(name.to_string()), args) InputObjectMeta::new::<T>(Cow::Owned(name.into()), args)
} }
} }

View file

@ -1,5 +1,6 @@
use crate::{ use crate::{
graphql_object, graphql_value, EmptyMutation, EmptySubscription, GraphQLEnum, RootNode, Value, graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLEnum,
RootNode, Value,
}; };
#[derive(GraphQLEnum)] #[derive(GraphQLEnum)]
@ -30,7 +31,7 @@ impl User {
(0..10) (0..10)
.map(|index| User { .map(|index| User {
id: index, id: index,
name: format!("user{}", index), name: format!("user{index}"),
kind: UserKind::User, kind: UserKind::User,
}) })
.collect() .collect()
@ -55,7 +56,7 @@ impl Query {
} }
async fn field_async_plain() -> String { async fn field_async_plain() -> String {
"field_async_plain".to_string() "field_async_plain".into()
} }
fn user(id: String) -> User { 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, &graphql_vars! {}, &())
let (res, errs) = crate::execute(doc, None, &schema, &vars, &())
.await .await
.unwrap(); .unwrap();

View file

@ -35,7 +35,7 @@ where
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let obj = result.as_object_value().expect("Result is not an object"); let obj = result.as_object_value().expect("Result is not an object");

View file

@ -22,7 +22,7 @@ struct TestType;
#[crate::graphql_object] #[crate::graphql_object]
impl TestType { impl TestType {
fn to_string(color: Color) -> String { fn to_string(color: Color) -> String {
format!("Color::{:?}", color) format!("Color::{color:?}")
} }
fn a_color() -> Color { fn a_color() -> Color {
@ -46,7 +46,7 @@ where
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let obj = result.as_object_value().expect("Result is not an object"); let obj = result.as_object_value().expect("Result is not an object");

View file

@ -96,7 +96,7 @@ mod field_execution {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -180,7 +180,7 @@ mod merge_parallel_fragments {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -288,7 +288,7 @@ mod merge_parallel_inline_fragments {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -355,7 +355,7 @@ mod threads_context_correctly {
&schema, &schema,
&vars, &vars,
&TestContext { &TestContext {
value: "Context value".to_owned(), value: "Context value".into(),
}, },
) )
.await .await
@ -363,7 +363,7 @@ mod threads_context_correctly {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!({"a": "Context value"})); assert_eq!(result, graphql_value!({"a": "Context value"}));
} }
@ -410,7 +410,7 @@ mod dynamic_context_switching {
let res = context let res = context
.items .items
.get(&key) .get(&key)
.ok_or(format!("Could not find key {}", key)) .ok_or(format!("Could not find key {key}"))
.map(|c| (c, ItemRef))?; .map(|c| (c, ItemRef))?;
Ok(res) Ok(res)
} }
@ -420,7 +420,7 @@ mod dynamic_context_switching {
key: i32, key: i32,
) -> FieldResult<Option<(&InnerContext, ItemRef)>> { ) -> FieldResult<Option<(&InnerContext, ItemRef)>> {
if key > 100 { if key > 100 {
Err(format!("Key too large: {}", key))?; Err(format!("Key too large: {key}"))?;
} }
Ok(context.items.get(&key).map(|c| (c, ItemRef))) Ok(context.items.get(&key).map(|c| (c, ItemRef)))
} }
@ -452,13 +452,13 @@ mod dynamic_context_switching {
( (
0, 0,
InnerContext { InnerContext {
value: "First value".to_owned(), value: "First value".into(),
}, },
), ),
( (
1, 1,
InnerContext { InnerContext {
value: "Second value".to_owned(), value: "Second value".into(),
}, },
), ),
] ]
@ -472,7 +472,7 @@ mod dynamic_context_switching {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -500,13 +500,13 @@ mod dynamic_context_switching {
( (
0, 0,
InnerContext { InnerContext {
value: "First value".to_owned(), value: "First value".into(),
}, },
), ),
( (
1, 1,
InnerContext { InnerContext {
value: "Second value".to_owned(), value: "Second value".into(),
}, },
), ),
] ]
@ -520,7 +520,7 @@ mod dynamic_context_switching {
assert_eq!(errs, vec![]); assert_eq!(errs, vec![]);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!({"first": {"value": "First value"}})); assert_eq!(result, graphql_value!({"first": {"value": "First value"}}));
} }
@ -542,13 +542,13 @@ mod dynamic_context_switching {
( (
0, 0,
InnerContext { InnerContext {
value: "First value".to_owned(), value: "First value".into(),
}, },
), ),
( (
1, 1,
InnerContext { 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)); assert_eq!(result, graphql_value!(null));
} }
@ -593,13 +593,13 @@ mod dynamic_context_switching {
( (
0, 0,
InnerContext { InnerContext {
value: "First value".to_owned(), value: "First value".into(),
}, },
), ),
( (
1, 1,
InnerContext { 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!( assert_eq!(
result, result,
@ -647,13 +647,13 @@ mod dynamic_context_switching {
( (
0, 0,
InnerContext { InnerContext {
value: "First value".to_owned(), value: "First value".into(),
}, },
), ),
( (
1, 1,
InnerContext { InnerContext {
value: "Second value".to_owned(), value: "Second value".into(),
}, },
), ),
] ]
@ -667,7 +667,7 @@ mod dynamic_context_switching {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!({"first": {"value": "First value"}})); assert_eq!(result, graphql_value!({"first": {"value": "First value"}}));
} }
@ -752,7 +752,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -783,7 +783,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!(null)); assert_eq!(result, graphql_value!(null));
@ -811,7 +811,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!(null)); assert_eq!(result, graphql_value!(null));
@ -839,7 +839,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!({"inner": {"nullableField": null}}),); assert_eq!(result, graphql_value!({"inner": {"nullableField": null}}),);
@ -867,7 +867,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!(null)); assert_eq!(result, graphql_value!(null));
@ -895,7 +895,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -926,7 +926,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!(result, graphql_value!(null)); assert_eq!(result, graphql_value!(null));
@ -954,7 +954,7 @@ mod propagates_errors_to_nullable_fields {
.await .await
.expect("Execution failed"); .expect("Execution failed");
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,

View file

@ -42,12 +42,12 @@ mod interface {
Schema { Schema {
pets: vec![ pets: vec![
Dog { Dog {
name: "Odie".to_owned(), name: "Odie".into(),
woofs: true, woofs: true,
} }
.into(), .into(),
Cat { Cat {
name: "Garfield".to_owned(), name: "Garfield".into(),
meows: false, meows: false,
} }
.into(), .into(),
@ -77,7 +77,7 @@ mod interface {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -170,11 +170,11 @@ mod union {
Schema { Schema {
pets: vec![ pets: vec![
Box::new(Dog { Box::new(Dog {
name: "Odie".to_owned(), name: "Odie".into(),
woofs: true, woofs: true,
}), }),
Box::new(Cat { Box::new(Cat {
name: "Garfield".to_owned(), name: "Garfield".into(),
meows: false, meows: false,
}), }),
], ],
@ -205,7 +205,7 @@ mod union {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,

View file

@ -92,7 +92,7 @@ where
F: Fn((&Object<DefaultScalarValue>, &Vec<Value<DefaultScalarValue>>)) -> (), F: Fn((&Object<DefaultScalarValue>, &Vec<Value<DefaultScalarValue>>)) -> (),
{ {
let schema = RootNode::new( let schema = RootNode::new(
Root {}, Root,
EmptyMutation::<()>::new(), EmptyMutation::<()>::new(),
EmptySubscription::<()>::new(), EmptySubscription::<()>::new(),
); );
@ -103,7 +103,7 @@ where
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let type_info = result let type_info = result
.as_object_value() .as_object_value()

View file

@ -117,7 +117,7 @@ where
F: Fn(&Object<DefaultScalarValue>, &Vec<Value<DefaultScalarValue>>) -> (), F: Fn(&Object<DefaultScalarValue>, &Vec<Value<DefaultScalarValue>>) -> (),
{ {
let schema = RootNode::new( let schema = RootNode::new(
Root {}, Root,
EmptyMutation::<()>::new(), EmptyMutation::<()>::new(),
EmptySubscription::<()>::new(), EmptySubscription::<()>::new(),
); );
@ -128,7 +128,7 @@ where
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let type_info = result let type_info = result
.as_object_value() .as_object_value()
@ -312,7 +312,7 @@ fn derive_derived() {
format!( format!(
"{:?}", "{:?}",
Derive { Derive {
field_one: "test".to_owned(), field_one: "test".into(),
}, },
), ),
"Derive { field_one: \"test\" }" "Derive { field_one: \"test\" }"

View file

@ -69,7 +69,7 @@ async fn test_execution() {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
assert_eq!( assert_eq!(
result, result,
@ -114,7 +114,7 @@ async fn enum_introspection() {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let type_info = result let type_info = result
.as_object_value() .as_object_value()
@ -223,7 +223,7 @@ async fn interface_introspection() {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let type_info = result let type_info = result
.as_object_value() .as_object_value()
@ -355,7 +355,7 @@ async fn object_introspection() {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let type_info = result let type_info = result
.as_object_value() .as_object_value()
@ -406,7 +406,7 @@ async fn object_introspection() {
assert_eq!(fields.len(), 2); assert_eq!(fields.len(), 2);
println!("Fields: {:#?}", fields); println!("Fields: {fields:#?}");
assert!(fields.contains(&graphql_value!({ assert!(fields.contains(&graphql_value!({
"name": "sampleEnum", "name": "sampleEnum",
@ -497,7 +497,7 @@ async fn scalar_introspection() {
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:#?}", result); println!("Result: {result:#?}");
let type_info = result let type_info = result
.as_object_value() .as_object_value()

View file

@ -23,7 +23,7 @@ impl TestComplexScalar {
v.as_string_value() v.as_string_value()
.filter(|s| *s == "SerializedValue") .filter(|s| *s == "SerializedValue")
.map(|_| Self) .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] #[graphql_object]
impl TestType { impl TestType {
fn field_with_object_input(input: Option<TestInputObject>) -> String { fn field_with_object_input(input: Option<TestInputObject>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn field_with_nullable_string_input(input: Option<String>) -> String { fn field_with_nullable_string_input(input: Option<String>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn field_with_non_nullable_string_input(input: String) -> String { fn field_with_non_nullable_string_input(input: String) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn field_with_default_argument_value( fn field_with_default_argument_value(
#[graphql(default = "Hello World")] input: String, #[graphql(default = "Hello World")] input: String,
) -> String { ) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn nullable_field_with_default_argument_value( fn nullable_field_with_default_argument_value(
#[graphql(default = "Hello World".to_owned())] input: Option<String>, #[graphql(default = "Hello World".to_owned())] input: Option<String>,
) -> String { ) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn field_with_nested_object_input(input: Option<TestNestedInputObject>) -> String { fn field_with_nested_object_input(input: Option<TestNestedInputObject>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn list(input: Option<Vec<Option<String>>>) -> String { fn list(input: Option<Vec<Option<String>>>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn nn_list(input: Vec<Option<String>>) -> String { fn nn_list(input: Vec<Option<String>>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn list_nn(input: Option<Vec<String>>) -> String { fn list_nn(input: Option<Vec<String>>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn nn_list_nn(input: Vec<String>) -> String { fn nn_list_nn(input: Vec<String>) -> String {
format!("{:?}", input) format!("{input:?}")
} }
fn example_input(arg: ExampleInputObject) -> String { fn example_input(arg: ExampleInputObject) -> String {
@ -110,11 +110,11 @@ impl TestType {
} }
fn integer_input(value: i32) -> String { fn integer_input(value: i32) -> String {
format!("value: {}", value) format!("value: {value}")
} }
fn float_input(value: f64) -> String { fn float_input(value: f64) -> String {
format!("value: {}", value) format!("value: {value}")
} }
} }
@ -134,7 +134,7 @@ where
assert_eq!(errs, []); assert_eq!(errs, []);
println!("Result: {:?}", result); println!("Result: {result:?}");
let obj = result.as_object_value().expect("Result is not an object"); let obj = result.as_object_value().expect("Result is not an object");

View file

@ -60,11 +60,8 @@ where
self.variables self.variables
.as_ref() .as_ref()
.and_then(|iv| { .and_then(|iv| {
iv.to_object_value().map(|o| { iv.to_object_value()
o.into_iter() .map(|o| o.into_iter().map(|(k, v)| (k.into(), v.clone())).collect())
.map(|(k, v)| (k.to_owned(), v.clone()))
.collect()
})
}) })
.unwrap_or_default() .unwrap_or_default()
} }
@ -635,20 +632,20 @@ pub mod tests {
"type":"connection_init", "type":"connection_init",
"payload":{} "payload":{}
}"# }"#
.to_owned(), .into(),
), ),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
"type":"connection_ack" "type":"connection_ack"
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT,
), ),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
"type":"ka" "type":"ka"
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT,
), ),
WsIntegrationMessage::Send( WsIntegrationMessage::Send(
@ -662,7 +659,7 @@ pub mod tests {
"query":"subscription { asyncHuman { id, name, homePlanet } }" "query":"subscription { asyncHuman { id, name, homePlanet } }"
} }
}"# }"#
.to_owned(), .into(),
), ),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
@ -678,7 +675,7 @@ pub mod tests {
} }
} }
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT,
), ),
]; ];
@ -688,7 +685,7 @@ pub mod tests {
async fn test_ws_invalid_json<T: WsIntegration>(integration: &T) { async fn test_ws_invalid_json<T: WsIntegration>(integration: &T) {
let messages = vec![ let messages = vec![
WsIntegrationMessage::Send("invalid json".to_owned()), WsIntegrationMessage::Send("invalid json".into()),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
"type":"connection_error", "type":"connection_error",
@ -696,7 +693,7 @@ pub mod tests {
"message":"serde error: expected value at line 1 column 1" "message":"serde error: expected value at line 1 column 1"
} }
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT,
), ),
]; ];
@ -711,20 +708,20 @@ pub mod tests {
"type":"connection_init", "type":"connection_init",
"payload":{} "payload":{}
}"# }"#
.to_owned(), .into(),
), ),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
"type":"connection_ack" "type":"connection_ack"
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT
), ),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
"type":"ka" "type":"ka"
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT
), ),
WsIntegrationMessage::Send( WsIntegrationMessage::Send(
@ -738,7 +735,7 @@ pub mod tests {
"query":"subscription { asyncHuman }" "query":"subscription { asyncHuman }"
} }
}"# }"#
.to_owned(), .into(),
), ),
WsIntegrationMessage::Expect( WsIntegrationMessage::Expect(
r#"{ r#"{
@ -752,7 +749,7 @@ pub mod tests {
}] }]
}] }]
}"# }"#
.to_owned(), .into(),
WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT
) )
]; ];

View file

@ -32,8 +32,6 @@ use crate::{graphql_scalar, InputValue, ScalarValue, Value};
type BigDecimal = bigdecimal::BigDecimal; type BigDecimal = bigdecimal::BigDecimal;
mod bigdecimal_scalar { mod bigdecimal_scalar {
use std::convert::TryFrom as _;
use super::*; use super::*;
pub(super) fn to_output<S: ScalarValue>(v: &BigDecimal) -> Value<S> { pub(super) fn to_output<S: ScalarValue>(v: &BigDecimal) -> Value<S> {
@ -45,13 +43,13 @@ mod bigdecimal_scalar {
Ok(BigDecimal::from(i)) Ok(BigDecimal::from(i))
} else if let Some(f) = v.as_float_value() { } else if let Some(f) = v.as_float_value() {
BigDecimal::try_from(f) 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 { } else {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
BigDecimal::from_str(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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{:?}`: {:?}", "failed to parse `{input:?}`: {:?}",
input,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = BigDecimal::from_input_value(&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(); 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}");
} }
} }
} }

View file

@ -14,9 +14,9 @@ mod object_id {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<ObjectId, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<ObjectId, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .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<S: ScalarValue>(v: &UtcDateTime) -> Value<S> { pub(super) fn to_output<S: ScalarValue>(v: &UtcDateTime) -> Value<S> {
Value::scalar( Value::scalar(
(*v).try_to_rfc3339_string() (*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<S: ScalarValue>(v: &InputValue<S>) -> Result<UtcDateTime, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<UtcDateTime, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
UtcDateTime::parse_rfc3339_str(s) UtcDateTime::parse_rfc3339_str(s)
.map_err(|e| format!("Failed to parse `UtcDateTime`: {}", e)) .map_err(|e| format!("Failed to parse `UtcDateTime`: {e}"))
}) })
} }
} }

View file

@ -62,9 +62,9 @@ mod date {
S: ScalarValue, S: ScalarValue,
{ {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .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, S: ScalarValue,
{ {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
// First, try to parse the most used format. // First, try to parse the most used format.
// At the end, try to parse the full format for the parsing // 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) 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_NO_SECS))
.or_else(|_| LocalTime::parse_from_str(s, FORMAT)) .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, S: ScalarValue,
{ {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
LocalDateTime::parse_from_str(s, FORMAT) 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, Tz: TimeZone + FromFixedOffset,
{ {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
DateTime::<FixedOffset>::parse_from_rfc3339(s) DateTime::<FixedOffset>::parse_from_rfc3339(s)
.map_err(|e| format!("Invalid `DateTime`: {}", e)) .map_err(|e| format!("Invalid `DateTime`: {e}"))
.map(FromFixedOffset::from_fixed_offset) .map(FromFixedOffset::from_fixed_offset)
}) })
} }
@ -345,11 +345,10 @@ mod date_test {
assert!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = Date::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = LocalTime::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = LocalDateTime::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = DateTime::<FixedOffset>::from_input_value(&input); let parsed = DateTime::<FixedOffset>::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(); let actual: InputValue = val.to_input_value();
assert_eq!(actual, expected, "on value: {}", val); assert_eq!(actual, expected, "on value: {val}");
} }
} }
} }

View file

@ -34,10 +34,10 @@ mod tz {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<TimeZone, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<TimeZone, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
s.parse::<TimeZone>() s.parse::<TimeZone>()
.map_err(|e| format!("Failed to parse `TimeZone`: {}", e)) .map_err(|e| format!("Failed to parse `TimeZone`: {e}"))
}) })
} }
} }

View file

@ -34,8 +34,6 @@ use crate::{graphql_scalar, InputValue, ScalarValue, Value};
type Decimal = rust_decimal::Decimal; type Decimal = rust_decimal::Decimal;
mod rust_decimal_scalar { mod rust_decimal_scalar {
use std::convert::TryFrom as _;
use super::*; use super::*;
pub(super) fn to_output<S: ScalarValue>(v: &Decimal) -> Value<S> { pub(super) fn to_output<S: ScalarValue>(v: &Decimal) -> Value<S> {
@ -46,14 +44,13 @@ mod rust_decimal_scalar {
if let Some(i) = v.as_int_value() { if let Some(i) = v.as_int_value() {
Ok(Decimal::from(i)) Ok(Decimal::from(i))
} else if let Some(f) = v.as_float_value() { } else if let Some(f) = v.as_float_value() {
Decimal::try_from(f) Decimal::try_from(f).map_err(|e| format!("Failed to parse `Decimal` from `Float`: {e}"))
.map_err(|e| format!("Failed to parse `Decimal` from `Float`: {}", e))
} else { } else {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
Decimal::from_str(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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{:?}`: {:?}", "failed to parse `{input:?}`: {:?}",
input,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = Decimal::from_input_value(&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"] { for raw in ["4.20", "0", "999.999999999", "875533788", "123", "43.44"] {
let actual: InputValue = Decimal::from_str(raw).unwrap().to_input_value(); 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}");
} }
} }
} }

View file

@ -1,8 +1,4 @@
use std::{ use std::{fmt, marker::PhantomData};
convert::{TryFrom as _, TryInto as _},
fmt,
marker::PhantomData,
};
use indexmap::IndexMap; use indexmap::IndexMap;
use serde::{ use serde::{
@ -251,7 +247,7 @@ impl Serialize for Spanning<ParseError> {
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
let mut map = ser.serialize_map(Some(2))?; 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_key("message")?;
map.serialize_value(&msg)?; map.serialize_value(&msg)?;
@ -396,7 +392,7 @@ mod tests {
#[test] #[test]
fn error_extensions() { fn error_extensions() {
let mut obj: Object<DefaultScalarValue> = Object::with_capacity(1); let mut obj: Object<DefaultScalarValue> = Object::with_capacity(1);
obj.add_field("foo".to_string(), Value::scalar("bar")); obj.add_field("foo", Value::scalar("bar"));
assert_eq!( assert_eq!(
to_string(&ExecutionError::at_origin(FieldError::new( to_string(&ExecutionError::at_origin(FieldError::new(
"foo error", "foo error",

View file

@ -57,14 +57,14 @@ mod date {
pub(super) fn to_output<S: ScalarValue>(v: &Date) -> Value<S> { pub(super) fn to_output<S: ScalarValue>(v: &Date) -> Value<S> {
Value::scalar( Value::scalar(
v.format(FORMAT) 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<S: ScalarValue>(v: &InputValue<S>) -> Result<Date, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Date, String> {
v.as_string_value() 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(s, FORMAT).map_err(|e| format!("Invalid `Date`: {}", e))) .and_then(|s| Date::parse(s, FORMAT).map_err(|e| format!("Invalid `Date`: {e}")))
} }
} }
@ -109,13 +109,13 @@ mod local_time {
} else { } else {
v.format(FORMAT) 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<S: ScalarValue>(v: &InputValue<S>) -> Result<LocalTime, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<LocalTime, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
// First, try to parse the most used format. // First, try to parse the most used format.
// At the end, try to parse the full format for the parsing // 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) LocalTime::parse(s, FORMAT_NO_MILLIS)
.or_else(|_| LocalTime::parse(s, FORMAT_NO_SECS)) .or_else(|_| LocalTime::parse(s, FORMAT_NO_SECS))
.or_else(|_| LocalTime::parse(s, FORMAT)) .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<S: ScalarValue>(v: &LocalDateTime) -> Value<S> { pub(super) fn to_output<S: ScalarValue>(v: &LocalDateTime) -> Value<S> {
Value::scalar( Value::scalar(
v.format(FORMAT) 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<S: ScalarValue>(v: &InputValue<S>) -> Result<LocalDateTime, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<LocalDateTime, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
LocalDateTime::parse(s, FORMAT) LocalDateTime::parse(s, FORMAT).map_err(|e| format!("Invalid `LocalDateTime`: {e}"))
.map_err(|e| format!("Invalid `LocalDateTime`: {}", e))
}) })
} }
} }
@ -186,15 +185,15 @@ mod date_time {
Value::scalar( Value::scalar(
v.to_offset(UtcOffset::UTC) v.to_offset(UtcOffset::UTC)
.format(&Rfc3339) .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<S: ScalarValue>(v: &InputValue<S>) -> Result<DateTime, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<DateTime, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .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)) .map(|dt| dt.to_offset(UtcOffset::UTC))
} }
@ -228,16 +227,16 @@ mod utc_offset {
pub(super) fn to_output<S: ScalarValue>(v: &UtcOffset) -> Value<S> { pub(super) fn to_output<S: ScalarValue>(v: &UtcOffset) -> Value<S> {
Value::scalar( Value::scalar(
v.format(UTC_OFFSET_FORMAT) 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<S: ScalarValue>(v: &InputValue<S>) -> Result<UtcOffset, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<UtcOffset, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| { .and_then(|s| {
UtcOffset::parse(s, UTC_OFFSET_FORMAT) 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = Date::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = LocalTime::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = LocalDateTime::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = DateTime::from_input_value(&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(); 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!( assert!(
parsed.is_ok(), parsed.is_ok(),
"failed to parse `{}`: {:?}", "failed to parse `{raw}`: {:?}",
raw,
parsed.unwrap_err(), 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 input: InputValue = input;
let parsed = UtcOffset::from_input_value(&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(); let actual: InputValue = val.to_input_value();
assert_eq!(actual, expected, "on value: {}", val); assert_eq!(actual, expected, "on value: {val}");
} }
} }
} }

View file

@ -14,8 +14,8 @@ mod url_scalar {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Url, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Url, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| Url::parse(s).map_err(|e| format!("Failed to parse `Url`: {}", e))) .and_then(|s| Url::parse(s).map_err(|e| format!("Failed to parse `Url`: {e}")))
} }
} }

View file

@ -16,8 +16,8 @@ mod uuid_scalar {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Uuid, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Uuid, String> {
v.as_string_value() v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {}", v)) .ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| Uuid::parse_str(s).map_err(|e| format!("Failed to parse `Uuid`: {}", e))) .and_then(|s| Uuid::parse_str(s).map_err(|e| format!("Failed to parse `Uuid`: {e}")))
} }
} }

View file

@ -5,15 +5,12 @@ pub(crate) const INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS: &str =
/// The desired GraphQL introspection format for the canonical query /// The desired GraphQL introspection format for the canonical query
/// (<https://github.com/graphql/graphql-js/blob/90bd6ff72625173dd39a1f82cfad9336cfad8f65/src/utilities/getIntrospectionQuery.ts#L62>) /// (<https://github.com/graphql/graphql-js/blob/90bd6ff72625173dd39a1f82cfad9336cfad8f65/src/utilities/getIntrospectionQuery.ts#L62>)
#[derive(Clone, Copy, Debug, Default)]
pub enum IntrospectionFormat { pub enum IntrospectionFormat {
/// The canonical GraphQL introspection query. /// The canonical GraphQL introspection query.
#[default]
All, All,
/// The canonical GraphQL introspection query without descriptions. /// The canonical GraphQL introspection query without descriptions.
WithoutDescriptions, WithoutDescriptions,
} }
impl Default for IntrospectionFormat {
fn default() -> Self {
IntrospectionFormat::All
}
}

View file

@ -6,6 +6,7 @@
// Required for using `juniper_codegen` macros inside this crate to resolve // Required for using `juniper_codegen` macros inside this crate to resolve
// absolute `::juniper` path correctly, without errors. // absolute `::juniper` path correctly, without errors.
extern crate core;
extern crate self as juniper; extern crate self as juniper;
use std::fmt; use std::fmt;
@ -108,10 +109,10 @@ pub enum GraphQLError {
impl fmt::Display for GraphQLError { impl fmt::Display for GraphQLError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Self::ParseError(e) => write!(f, "{}", e), Self::ParseError(e) => write!(f, "{e}"),
Self::ValidationError(errs) => { Self::ValidationError(errs) => {
for e in errs { for e in errs {
writeln!(f, "{}", e)?; writeln!(f, "{e}")?;
} }
Ok(()) Ok(())
} }

View file

@ -217,37 +217,35 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": 123}, graphql_vars! {"key": 123},
vec![("key".to_owned(), IV::scalar(123))] vec![("key".into(), IV::scalar(123))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": "val"}, graphql_vars! {"key": "val"},
vec![("key".to_owned(), IV::scalar("val"))] vec![("key".into(), IV::scalar("val"))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": 1.23}, graphql_vars! {"key": 1.23},
vec![("key".to_owned(), IV::scalar(1.23))] vec![("key".into(), IV::scalar(1.23))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": 1 + 2}, graphql_vars! {"key": 1 + 2},
vec![("key".to_owned(), IV::scalar(3))] vec![("key".into(), IV::scalar(3))].into_iter().collect(),
.into_iter()
.collect(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": false}, graphql_vars! {"key": false},
vec![("key".to_owned(), IV::scalar(false))] vec![("key".into(), IV::scalar(false))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": (val)}, graphql_vars! {"key": (val)},
vec![("key".to_owned(), IV::scalar(42))] vec![("key".into(), IV::scalar(42))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
@ -257,13 +255,13 @@ mod tests {
fn r#enum() { fn r#enum() {
assert_eq!( assert_eq!(
graphql_vars! {"key": ENUM}, graphql_vars! {"key": ENUM},
vec![("key".to_owned(), IV::enum_value("ENUM"))] vec![("key".into(), IV::enum_value("ENUM"))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": lowercase}, graphql_vars! {"key": lowercase},
vec![("key".to_owned(), IV::enum_value("lowercase"))] vec![("key".into(), IV::enum_value("lowercase"))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
@ -273,19 +271,19 @@ mod tests {
fn variable() { fn variable() {
assert_eq!( assert_eq!(
graphql_vars! {"key": @var}, graphql_vars! {"key": @var},
vec![("key".to_owned(), IV::variable("var"))] vec![("key".into(), IV::variable("var"))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": @array}, graphql_vars! {"key": @array},
vec![("key".to_owned(), IV::variable("array"))] vec![("key".into(), IV::variable("array"))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": @object}, graphql_vars! {"key": @object},
vec![("key".to_owned(), IV::variable("object"))] vec![("key".into(), IV::variable("object"))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
@ -297,68 +295,65 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": []}, graphql_vars! {"key": []},
vec![("key".to_owned(), IV::list(vec![]))] vec![("key".into(), IV::list(vec![]))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [null]}, graphql_vars! {"key": [null]},
vec![("key".to_owned(), IV::list(vec![IV::Null]))] vec![("key".into(), IV::list(vec![IV::Null]))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [1]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [1 + 2]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [(val)]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [ENUM]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [lowercase]}, graphql_vars! {"key": [lowercase]},
vec![( vec![("key".into(), IV::list(vec![IV::enum_value("lowercase")]))]
"key".to_owned(), .into_iter()
IV::list(vec![IV::enum_value("lowercase")]) .collect::<V>(),
)]
.into_iter()
.collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [@var]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [@array]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": [@object]}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
@ -366,7 +361,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": [1, [2], 3]}, graphql_vars! {"key": [1, [2], 3]},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::list(vec![ IV::list(vec![
IV::scalar(1), IV::scalar(1),
IV::list(vec![IV::scalar(2)]), IV::list(vec![IV::scalar(2)]),
@ -379,7 +374,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": [1, [2 + 3], 3]}, graphql_vars! {"key": [1, [2 + 3], 3]},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::list(vec![ IV::list(vec![
IV::scalar(1), IV::scalar(1),
IV::list(vec![IV::scalar(5)]), IV::list(vec![IV::scalar(5)]),
@ -392,7 +387,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": [1, [ENUM], (val)]}, graphql_vars! {"key": [1, [ENUM], (val)]},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::list(vec![ IV::list(vec![
IV::scalar(1), IV::scalar(1),
IV::list(vec![IV::enum_value("ENUM")]), IV::list(vec![IV::enum_value("ENUM")]),
@ -405,7 +400,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": [1 + 2, [(val)], @val]}, graphql_vars! {"key": [1 + 2, [(val)], @val]},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::list(vec![ IV::list(vec![
IV::scalar(3), IV::scalar(3),
IV::list(vec![IV::scalar(42)]), IV::list(vec![IV::scalar(42)]),
@ -418,7 +413,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": [1, [@val], ENUM]}, graphql_vars! {"key": [1, [@val], ENUM]},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::list(vec![ IV::list(vec![
IV::scalar(1), IV::scalar(1),
IV::list(vec![IV::variable("val")]), IV::list(vec![IV::variable("val")]),
@ -436,14 +431,14 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {}}, graphql_vars! {"key": {}},
vec![("key".to_owned(), IV::object(IndexMap::<String, _>::new()))] vec![("key".into(), IV::object(IndexMap::<String, _>::new()))]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": null}}, 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() .into_iter()
.collect::<V>(), .collect::<V>(),
); );
@ -451,7 +446,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": 123}}, graphql_vars! {"key": {"key": 123}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::scalar(123)}), IV::object(indexmap! {"key" => IV::scalar(123)}),
)] )]
.into_iter() .into_iter()
@ -459,17 +454,14 @@ mod tests {
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": 1 + 2}}, graphql_vars! {"key": {"key": 1 + 2}},
vec![( vec![("key".into(), IV::object(indexmap! {"key" => IV::scalar(3)}),)]
"key".to_owned(), .into_iter()
IV::object(indexmap! {"key" => IV::scalar(3)}), .collect::<V>(),
)]
.into_iter()
.collect::<V>(),
); );
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": (val)}}, graphql_vars! {"key": {"key": (val)}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::scalar(42)}), IV::object(indexmap! {"key" => IV::scalar(42)}),
)] )]
.into_iter() .into_iter()
@ -479,7 +471,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": []}}, graphql_vars! {"key": {"key": []}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::list(vec![])}), IV::object(indexmap! {"key" => IV::list(vec![])}),
)] )]
.into_iter() .into_iter()
@ -488,7 +480,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": [null]}}, graphql_vars! {"key": {"key": [null]}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::list(vec![IV::Null])}), IV::object(indexmap! {"key" => IV::list(vec![IV::Null])}),
)] )]
.into_iter() .into_iter()
@ -497,7 +489,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": [1]}}, graphql_vars! {"key": {"key": [1]}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(1)])}), IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(1)])}),
)] )]
.into_iter() .into_iter()
@ -506,7 +498,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": [1 + 2]}}, graphql_vars! {"key": {"key": [1 + 2]}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(3)])}), IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(3)])}),
)] )]
.into_iter() .into_iter()
@ -515,7 +507,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": [(val)]}}, graphql_vars! {"key": {"key": [(val)]}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(42)])}), IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(42)])}),
)] )]
.into_iter() .into_iter()
@ -524,7 +516,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": ENUM}}, graphql_vars! {"key": {"key": ENUM}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::enum_value("ENUM")}), IV::object(indexmap! {"key" => IV::enum_value("ENUM")}),
)] )]
.into_iter() .into_iter()
@ -533,7 +525,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": lowercase}}, graphql_vars! {"key": {"key": lowercase}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::enum_value("lowercase")}), IV::object(indexmap! {"key" => IV::enum_value("lowercase")}),
)] )]
.into_iter() .into_iter()
@ -542,7 +534,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": @val}}, graphql_vars! {"key": {"key": @val}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::variable("val")}), IV::object(indexmap! {"key" => IV::variable("val")}),
)] )]
.into_iter() .into_iter()
@ -551,7 +543,7 @@ mod tests {
assert_eq!( assert_eq!(
graphql_vars! {"key": {"key": @array}}, graphql_vars! {"key": {"key": @array}},
vec![( vec![(
"key".to_owned(), "key".into(),
IV::object(indexmap! {"key" => IV::variable("array")}), IV::object(indexmap! {"key" => IV::variable("array")}),
)] )]
.into_iter() .into_iter()
@ -576,7 +568,7 @@ mod tests {
}, },
vec![ vec![
( (
"inner".to_owned(), "inner".into(),
IV::object(indexmap! { IV::object(indexmap! {
"key1" => IV::scalar(42), "key1" => IV::scalar(42),
"key2" => IV::scalar("val"), "key2" => IV::scalar("val"),
@ -602,7 +594,7 @@ mod tests {
]), ]),
}), }),
), ),
("more".to_owned(), IV::variable("var")), ("more".into(), IV::variable("var")),
] ]
.into_iter() .into_iter()
.collect::<V>(), .collect::<V>(),

View file

@ -41,8 +41,7 @@ where
/// [`GraphQLType::name`]: crate::GraphQLType::name /// [`GraphQLType::name`]: crate::GraphQLType::name
pub fn err_unnamed_type<S>(name: &str) -> FieldError<S> { pub fn err_unnamed_type<S>(name: &str) -> FieldError<S> {
FieldError::from(format!( FieldError::from(format!(
"Expected `{}` type to implement `GraphQLType::name`", "Expected `{name}` type to implement `GraphQLType::name`",
name,
)) ))
} }

View file

@ -239,7 +239,7 @@ impl<'a> Lexer<'a> {
c if escaped => { c if escaped => {
return Err(Spanning::zero_width( return Err(Spanning::zero_width(
&old_pos, &old_pos,
LexerError::UnknownEscapeSequence(format!("\\{}", c)), LexerError::UnknownEscapeSequence(format!("\\{c}")),
)); ));
} }
'\\' => escaped = true, '\\' => escaped = true,
@ -305,14 +305,14 @@ impl<'a> Lexer<'a> {
if len != 4 { if len != 4 {
return Err(Spanning::zero_width( return Err(Spanning::zero_width(
start_pos, start_pos,
LexerError::UnknownEscapeSequence("\\u".to_owned() + escape), LexerError::UnknownEscapeSequence(format!("\\u{escape}")),
)); ));
} }
let code_point = u32::from_str_radix(escape, 16).map_err(|_| { let code_point = u32::from_str_radix(escape, 16).map_err(|_| {
Spanning::zero_width( Spanning::zero_width(
start_pos, 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> { impl<'a> fmt::Display for Token<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Token::Name(name) => write!(f, "{}", name), Token::Name(name) => write!(f, "{name}"),
Token::Scalar(ScalarToken::Int(s)) | Token::Scalar(ScalarToken::Float(s)) => { Token::Scalar(ScalarToken::Int(s)) | Token::Scalar(ScalarToken::Float(s)) => {
write!(f, "{}", s) write!(f, "{s}")
} }
Token::Scalar(ScalarToken::String(s)) => { Token::Scalar(ScalarToken::String(s)) => {
write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
@ -529,15 +529,15 @@ fn is_number_start(c: char) -> bool {
impl fmt::Display for LexerError { impl fmt::Display for LexerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { 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::UnterminatedString => write!(f, "Unterminated string literal"),
LexerError::UnknownCharacterInString(c) => { LexerError::UnknownCharacterInString(c) => {
write!(f, "Unknown character \"{}\" in string literal", c) write!(f, "Unknown character \"{c}\" in string literal")
} }
LexerError::UnknownEscapeSequence(ref s) => { 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::UnexpectedEndOfFile => write!(f, "Unexpected end of input"),
LexerError::InvalidNumber => write!(f, "Invalid number literal"), LexerError::InvalidNumber => write!(f, "Invalid number literal"),
} }

View file

@ -25,7 +25,7 @@ pub enum ParseError {
impl fmt::Display for ParseError { impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { 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::UnexpectedEndOfFile => write!(f, "Unexpected end of input"),
Self::LexerError(e) => e.fmt(f), Self::LexerError(e) => e.fmt(f),
Self::ExpectedScalarError(e) => e.fmt(f), Self::ExpectedScalarError(e) => e.fmt(f),
@ -53,7 +53,7 @@ impl ParseError {
let mut s = String::new(); let mut s = String::new();
// PANIC: Unwrapping is OK here, as it may panic only on allocation // PANIC: Unwrapping is OK here, as it may panic only on allocation
// error. // error.
write!(s, "{}", token).unwrap(); write!(s, "{token}").unwrap();
Self::UnexpectedToken(s) Self::UnexpectedToken(s)
} }

View file

@ -16,7 +16,7 @@ where
s, s,
&SchemaType::new::<QueryRoot, MutationRoot, SubscriptionRoot>(&(), &(), &()), &SchemaType::new::<QueryRoot, MutationRoot, SubscriptionRoot>(&(), &(), &()),
) )
.expect(&format!("Parse error on input {:#?}", s)) .expect(&format!("Parse error on input {s:#?}"))
} }
fn parse_document_error<S: ScalarValue>(s: &str) -> Spanning<ParseError> { fn parse_document_error<S: ScalarValue>(s: &str) -> Spanning<ParseError> {
@ -24,7 +24,7 @@ fn parse_document_error<S: ScalarValue>(s: &str) -> Spanning<ParseError> {
s, s,
&SchemaType::new::<QueryRoot, MutationRoot, SubscriptionRoot>(&(), &(), &()), &SchemaType::new::<QueryRoot, MutationRoot, SubscriptionRoot>(&(), &(), &()),
) { ) {
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, Err(err) => err,
} }
} }

View file

@ -13,8 +13,8 @@ fn tokenize_to_vec<'a>(s: &'a str) -> Vec<Spanning<Token<'a>>> {
break; break;
} }
} }
Some(Err(e)) => panic!("Error in input stream: {:#?} for {:#?}", e, s), Some(Err(e)) => panic!("Error in input stream: {e:#?} for {s:#?}"),
None => panic!("EOF before EndOfFile token in {:#?}", s), None => panic!("EOF before EndOfFile token in {s:#?}"),
} }
} }
@ -37,13 +37,13 @@ fn tokenize_error(s: &str) -> Spanning<LexerError> {
match lexer.next() { match lexer.next() {
Some(Ok(t)) => { Some(Ok(t)) => {
if t.item == Token::EndOfFile { if t.item == Token::EndOfFile {
panic!("Tokenizer did not return error for {:#?}", s); panic!("Tokenizer did not return error for {s:#?}");
} }
} }
Some(Err(e)) => { Some(Err(e)) => {
return 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( Spanning::start_end(
&SourcePosition::new(0, 0, 0), &SourcePosition::new(0, 0, 0),
&SourcePosition::new(34, 0, 34), &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("\""), tokenize_error("\""),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(1, 0, 1), &SourcePosition::new(1, 0, 1),
LexerError::UnterminatedString LexerError::UnterminatedString,
) )
); );
@ -215,7 +215,7 @@ fn string_errors() {
tokenize_error("\"no end quote"), tokenize_error("\"no end quote"),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(13, 0, 13), &SourcePosition::new(13, 0, 13),
LexerError::UnterminatedString LexerError::UnterminatedString,
) )
); );
@ -223,7 +223,7 @@ fn string_errors() {
tokenize_error("\"contains unescaped \u{0007} control char\""), tokenize_error("\"contains unescaped \u{0007} control char\""),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(20, 0, 20), &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\""), tokenize_error("\"null-byte is not \u{0000} end of file\""),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(18, 0, 18), &SourcePosition::new(18, 0, 18),
LexerError::UnknownCharacterInString('\u{0000}') LexerError::UnknownCharacterInString('\u{0000}'),
) )
); );
@ -239,7 +239,7 @@ fn string_errors() {
tokenize_error("\"multi\nline\""), tokenize_error("\"multi\nline\""),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &SourcePosition::new(6, 0, 6),
LexerError::UnterminatedString LexerError::UnterminatedString,
) )
); );
@ -247,7 +247,7 @@ fn string_errors() {
tokenize_error("\"multi\rline\""), tokenize_error("\"multi\rline\""),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &SourcePosition::new(6, 0, 6),
LexerError::UnterminatedString LexerError::UnterminatedString,
) )
); );
@ -255,7 +255,7 @@ fn string_errors() {
tokenize_error(r#""bad \z esc""#), tokenize_error(r#""bad \z esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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""#), tokenize_error(r#""bad \x esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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""#), tokenize_error(r#""bad \u1 esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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""#), tokenize_error(r#""bad \u0XX1 esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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""#), tokenize_error(r#""bad \uXXXX esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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""#), tokenize_error(r#""bad \uFXXX esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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""#), tokenize_error(r#""bad \uXXXF esc""#),
Spanning::zero_width( Spanning::zero_width(
&SourcePosition::new(6, 0, 6), &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)) => { Token::Scalar(ScalarToken::Float(actual)) => {
assert!( assert!(
expected == actual, expected == actual,
"[expected] {} != {} [actual]", "[expected] {expected} != {actual} [actual]",
expected,
actual
); );
} }
_ => assert!(false), _ => assert!(false),
@ -662,39 +660,32 @@ fn punctuation_error() {
#[test] #[test]
fn display() { fn display() {
assert_eq!(format!("{}", Token::Name("identifier")), "identifier"); for (input, expected) in [
(Token::Name("identifier"), "identifier"),
assert_eq!(format!("{}", Token::Scalar(ScalarToken::Int("123"))), "123"); (Token::Scalar(ScalarToken::Int("123")), "123"),
(Token::Scalar(ScalarToken::Float("4.5")), "4.5"),
assert_eq!( (
format!("{}", Token::Scalar(ScalarToken::Float("4.5"))), Token::Scalar(ScalarToken::String("some string")),
"4.5" "\"some string\"",
);
assert_eq!(
format!("{}", Token::Scalar(ScalarToken::String("some string"))),
"\"some string\""
);
assert_eq!(
format!(
"{}",
Token::Scalar(ScalarToken::String("string with \\ escape and \" quote"))
), ),
"\"string with \\\\ escape and \\\" quote\"" (
); Token::Scalar(ScalarToken::String("string with \\ escape and \" quote")),
"\"string with \\\\ escape and \\\" quote\"",
assert_eq!(format!("{}", Token::ExclamationMark), "!"); ),
assert_eq!(format!("{}", Token::Dollar), "$"); (Token::ExclamationMark, "!"),
assert_eq!(format!("{}", Token::ParenOpen), "("); (Token::Dollar, "$"),
assert_eq!(format!("{}", Token::ParenClose), ")"); (Token::ParenOpen, "("),
assert_eq!(format!("{}", Token::BracketOpen), "["); (Token::ParenClose, ")"),
assert_eq!(format!("{}", Token::BracketClose), "]"); (Token::BracketOpen, "["),
assert_eq!(format!("{}", Token::CurlyOpen), "{"); (Token::BracketClose, "]"),
assert_eq!(format!("{}", Token::CurlyClose), "}"); (Token::CurlyOpen, "{"),
assert_eq!(format!("{}", Token::Ellipsis), "..."); (Token::CurlyClose, "}"),
assert_eq!(format!("{}", Token::Colon), ":"); (Token::Ellipsis, "..."),
assert_eq!(format!("{}", Token::Equals), "="); (Token::Colon, ":"),
assert_eq!(format!("{}", Token::At), "@"); (Token::Equals, "="),
assert_eq!(format!("{}", Token::Pipe), "|"); (Token::At, "@"),
(Token::Pipe, "|"),
] {
assert_eq!(input.to_string(), expected);
}
} }

View file

@ -65,11 +65,11 @@ where
S: ScalarValue, S: ScalarValue,
{ {
let mut lexer = Lexer::new(s); 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::<Query, EmptyMutation<()>, EmptySubscription<()>>(&(), &(), &()); let schema = SchemaType::new::<Query, EmptyMutation<()>, EmptySubscription<()>>(&(), &(), &());
parse_value_literal(&mut parser, false, &schema, Some(meta)) parse_value_literal(&mut parser, false, &schema, Some(meta))
.expect(&format!("Parse error on input {:#?}", s)) .expect(&format!("Parse error on input {s:#?}"))
} }
#[test] #[test]

View file

@ -455,7 +455,7 @@ impl<'a, S> ScalarMeta<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -525,7 +525,7 @@ impl<'a, S> ObjectMeta<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -536,7 +536,7 @@ impl<'a, S> ObjectMeta<'a, S> {
pub fn interfaces(mut self, interfaces: &[Type<'a>]) -> Self { pub fn interfaces(mut self, interfaces: &[Type<'a>]) -> Self {
self.interface_names = interfaces self.interface_names = interfaces
.iter() .iter()
.map(|t| t.innermost_name().to_owned()) .map(|t| t.innermost_name().into())
.collect(); .collect();
self self
} }
@ -568,7 +568,7 @@ impl<'a, S> EnumMeta<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -598,7 +598,7 @@ impl<'a, S> InterfaceMeta<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -609,7 +609,7 @@ impl<'a, S> InterfaceMeta<'a, S> {
pub fn interfaces(mut self, interfaces: &[Type<'a>]) -> Self { pub fn interfaces(mut self, interfaces: &[Type<'a>]) -> Self {
self.interface_names = interfaces self.interface_names = interfaces
.iter() .iter()
.map(|t| t.innermost_name().to_owned()) .map(|t| t.innermost_name().into())
.collect(); .collect();
self self
} }
@ -627,10 +627,7 @@ impl<'a> UnionMeta<'a> {
Self { Self {
name, name,
description: None, description: None,
of_type_names: of_types of_type_names: of_types.iter().map(|t| t.innermost_name().into()).collect(),
.iter()
.map(|t| t.innermost_name().to_owned())
.collect(),
} }
} }
@ -639,7 +636,7 @@ impl<'a> UnionMeta<'a> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -671,7 +668,7 @@ impl<'a, S> InputObjectMeta<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -687,7 +684,7 @@ impl<'a, S> Field<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -712,7 +709,7 @@ impl<'a, S> Field<'a, S> {
/// Overwrites any previously set deprecation reason. /// Overwrites any previously set deprecation reason.
#[must_use] #[must_use]
pub fn deprecated(mut self, reason: Option<&str>) -> Self { 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 self
} }
} }
@ -721,7 +718,7 @@ impl<'a, S> Argument<'a, S> {
/// Builds a new [`Argument`] of the given [`Type`] with the given `name`. /// Builds a new [`Argument`] of the given [`Type`] with the given `name`.
pub fn new(name: &str, arg_type: Type<'a>) -> Self { pub fn new(name: &str, arg_type: Type<'a>) -> Self {
Self { Self {
name: name.to_owned(), name: name.into(),
description: None, description: None,
arg_type, arg_type,
default_value: None, default_value: None,
@ -733,7 +730,7 @@ impl<'a, S> Argument<'a, S> {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -751,7 +748,7 @@ impl EnumValue {
/// Constructs a new [`EnumValue`] with the provided `name`. /// Constructs a new [`EnumValue`] with the provided `name`.
pub fn new(name: &str) -> Self { pub fn new(name: &str) -> Self {
Self { Self {
name: name.to_owned(), name: name.into(),
description: None, description: None,
deprecation_status: DeprecationStatus::Current, deprecation_status: DeprecationStatus::Current,
} }
@ -762,7 +759,7 @@ impl EnumValue {
/// Overwrites any previously set description. /// Overwrites any previously set description.
#[must_use] #[must_use]
pub fn description(mut self, description: &str) -> Self { pub fn description(mut self, description: &str) -> Self {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
@ -771,7 +768,7 @@ impl EnumValue {
/// Overwrites any previously set deprecation reason. /// Overwrites any previously set deprecation reason.
#[must_use] #[must_use]
pub fn deprecated(mut self, reason: Option<&str>) -> Self { 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 self
} }
} }

View file

@ -167,8 +167,7 @@ where
/// [GraphQL Schema Language](https://graphql.org/learn/schema/#type-language) /// [GraphQL Schema Language](https://graphql.org/learn/schema/#type-language)
/// format. /// format.
pub fn as_schema_language(&self) -> String { pub fn as_schema_language(&self) -> String {
let doc = self.as_parser_document(); self.as_parser_document().to_string()
format!("{}", doc)
} }
#[cfg(feature = "graphql-parser")] #[cfg(feature = "graphql-parser")]
@ -210,17 +209,14 @@ impl<'a, S> SchemaType<'a, S> {
registry.get_type::<SchemaType<S>>(&()); registry.get_type::<SchemaType<S>>(&());
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( directives.insert(
"include".to_owned(), "deprecated".into(),
DirectiveType::new_include(&mut registry),
);
directives.insert(
"deprecated".to_owned(),
DirectiveType::new_deprecated(&mut registry), DirectiveType::new_deprecated(&mut registry),
); );
directives.insert( directives.insert(
"specifiedBy".to_owned(), "specifiedBy".into(),
DirectiveType::new_specified_by(&mut registry), DirectiveType::new_specified_by(&mut registry),
); );
@ -243,7 +239,7 @@ impl<'a, S> SchemaType<'a, S> {
for meta_type in registry.types.values() { for meta_type in registry.types.values() {
if let MetaType::Placeholder(PlaceholderMeta { ref of_type }) = *meta_type { 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 { SchemaType {
@ -508,9 +504,9 @@ where
locations: &[DirectiveLocation], locations: &[DirectiveLocation],
arguments: &[Argument<'a, S>], arguments: &[Argument<'a, S>],
is_repeatable: bool, is_repeatable: bool,
) -> DirectiveType<'a, S> { ) -> Self {
DirectiveType { Self {
name: name.to_owned(), name: name.into(),
description: None, description: None,
locations: locations.to_vec(), locations: locations.to_vec(),
arguments: arguments.to_vec(), arguments: arguments.to_vec(),
@ -578,7 +574,7 @@ where
} }
pub fn description(mut self, description: &str) -> DirectiveType<'a, S> { pub fn description(mut self, description: &str) -> DirectiveType<'a, S> {
self.description = Some(description.to_owned()); self.description = Some(description.into());
self self
} }
} }
@ -605,8 +601,8 @@ impl<'a, S> fmt::Display for TypeType<'a, S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Self::Concrete(t) => f.write_str(t.name().unwrap()), Self::Concrete(t) => f.write_str(t.name().unwrap()),
Self::List(i, _) => write!(f, "[{}]", i), Self::List(i, _) => write!(f, "[{i}]"),
Self::NonNull(i) => write!(f, "{}!", i), Self::NonNull(i) => write!(f, "{i}!"),
} }
} }
} }
@ -644,10 +640,7 @@ mod test {
"#, "#,
) )
.unwrap(); .unwrap();
assert_eq!( assert_eq!(ast.to_string(), schema.as_parser_document().to_string());
format!("{}", ast),
format!("{}", schema.as_parser_document()),
);
} }
} }
@ -691,10 +684,10 @@ mod test {
} }
/// This is whatever's description. /// This is whatever's description.
fn whatever() -> String { fn whatever() -> String {
"foo".to_string() "foo".into()
} }
fn arr(stuff: Vec<Coordinate>) -> Option<&'static str> { fn arr(stuff: Vec<Coordinate>) -> Option<&'static str> {
(!stuff.is_empty()).then(|| "stuff") (!stuff.is_empty()).then_some("stuff")
} }
fn fruit() -> Fruit { fn fruit() -> Fruit {
Fruit::Apple Fruit::Apple
@ -754,7 +747,7 @@ mod test {
"#, "#,
) )
.unwrap(); .unwrap();
assert_eq!(format!("{}", ast), schema.as_schema_language()); assert_eq!(ast.to_string(), schema.as_schema_language());
} }
} }
} }

View file

@ -288,16 +288,16 @@ impl<'a, S: ScalarValue + 'a> TypeType<'a, S> {
.iter() .iter()
.filter_map(|&ct| { .filter_map(|&ct| {
if let MetaType::Object(ObjectMeta { if let MetaType::Object(ObjectMeta {
ref name, name,
ref interface_names, interface_names,
.. ..
}) = *ct }) = ct
{ {
if interface_names.contains(&iface_name.to_string()) { interface_names
context.type_by_name(name) .iter()
} else { .any(|name| name == iface_name)
None .then(|| context.type_by_name(name))
} .flatten()
} else { } else {
None None
} }

View file

@ -285,15 +285,11 @@ where
DeprecationStatus::Current => None, DeprecationStatus::Current => None,
DeprecationStatus::Deprecated(reason) => Some(ExternalDirective { DeprecationStatus::Deprecated(reason) => Some(ExternalDirective {
position: Pos::default(), position: Pos::default(),
name: From::from("deprecated"), name: "deprecated".into(),
arguments: if let Some(reason) = reason { arguments: reason
vec![( .as_ref()
From::from("reason"), .map(|rsn| vec![(From::from("reason"), ExternalValue::String(rsn.into()))])
ExternalValue::String(reason.to_string()), .unwrap_or_default(),
)]
} else {
vec![]
},
}), }),
} }
} }

View file

@ -93,12 +93,12 @@ impl Human {
home_planet: Option<&str>, home_planet: Option<&str>,
) -> Self { ) -> Self {
Self { Self {
id: id.to_owned(), id: id.into(),
name: name.to_owned(), name: name.into(),
friend_ids: friend_ids.iter().copied().map(ToOwned::to_owned).collect(), friend_ids: friend_ids.iter().copied().map(Into::into).collect(),
appears_in: appears_in.to_vec(), appears_in: appears_in.to_vec(),
secret_backstory: secret_backstory.map(ToOwned::to_owned), secret_backstory: secret_backstory.map(Into::into),
home_planet: home_planet.map(|p| p.to_owned()), home_planet: home_planet.map(Into::into),
} }
} }
} }
@ -153,12 +153,12 @@ impl Droid {
primary_function: Option<&str>, primary_function: Option<&str>,
) -> Self { ) -> Self {
Self { Self {
id: id.to_owned(), id: id.into(),
name: name.to_owned(), name: name.into(),
friend_ids: friend_ids.iter().copied().map(ToOwned::to_owned).collect(), friend_ids: friend_ids.iter().copied().map(Into::into).collect(),
appears_in: appears_in.to_vec(), appears_in: appears_in.to_vec(),
secret_backstory: secret_backstory.map(ToOwned::to_owned), secret_backstory: secret_backstory.map(Into::into),
primary_function: primary_function.map(ToOwned::to_owned), primary_function: primary_function.map(Into::into),
} }
} }
} }
@ -192,7 +192,7 @@ impl Droid {
} }
} }
#[derive(Default, Clone)] #[derive(Clone, Default)]
pub struct Database { pub struct Database {
humans: HashMap<String, Human>, humans: HashMap<String, Human>,
droids: HashMap<String, Droid>, droids: HashMap<String, Droid>,
@ -206,7 +206,7 @@ impl Database {
let mut droids = HashMap::new(); let mut droids = HashMap::new();
humans.insert( humans.insert(
"1000".to_owned(), "1000".into(),
Human::new( Human::new(
"1000", "1000",
"Luke Skywalker", "Luke Skywalker",
@ -218,7 +218,7 @@ impl Database {
); );
humans.insert( humans.insert(
"1001".to_owned(), "1001".into(),
Human::new( Human::new(
"1001", "1001",
"Darth Vader", "Darth Vader",
@ -230,7 +230,7 @@ impl Database {
); );
humans.insert( humans.insert(
"1002".to_owned(), "1002".into(),
Human::new( Human::new(
"1002", "1002",
"Han Solo", "Han Solo",
@ -242,7 +242,7 @@ impl Database {
); );
humans.insert( humans.insert(
"1003".to_owned(), "1003".into(),
Human::new( Human::new(
"1003", "1003",
"Leia Organa", "Leia Organa",
@ -254,7 +254,7 @@ impl Database {
); );
humans.insert( humans.insert(
"1004".to_owned(), "1004".into(),
Human::new( Human::new(
"1004", "1004",
"Wilhuff Tarkin", "Wilhuff Tarkin",
@ -266,7 +266,7 @@ impl Database {
); );
droids.insert( droids.insert(
"2000".to_owned(), "2000".into(),
Droid::new( Droid::new(
"2000", "2000",
"C-3PO", "C-3PO",
@ -278,7 +278,7 @@ impl Database {
); );
droids.insert( droids.insert(
"2001".to_owned(), "2001".into(),
Droid::new( Droid::new(
"2001", "2001",
"R2-D2", "R2-D2",

View file

@ -1,4 +1,4 @@
use std::{iter, iter::FromIterator as _, pin::Pin}; use std::{iter, pin::Pin};
use futures::{stream, StreamExt as _}; use futures::{stream, StreamExt as _};
@ -48,9 +48,9 @@ impl MySubscription {
async fn async_human() -> HumanStream { async fn async_human() -> HumanStream {
Box::pin(stream::once(async { Box::pin(stream::once(async {
Human { Human {
id: "stream id".to_string(), id: "stream id".into(),
name: "stream name".to_string(), name: "stream name".into(),
home_planet: "stream home planet".to_string(), home_planet: "stream home planet".into(),
} }
})) }))
} }
@ -78,7 +78,7 @@ impl MySubscription {
Human { Human {
id, id,
name, name,
home_planet: "default home planet".to_string(), home_planet: "default home planet".into(),
} }
})) }))
} }
@ -154,10 +154,10 @@ fn returns_requested_object() {
id id
name 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 mut iterator_count = 0;
let expected_values = vec![vec![Ok(Value::Object(Object::from_iter( let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(
@ -182,10 +182,9 @@ fn returns_error() {
id id
name name
} }
}"# }"#;
.to_string();
let response = create_and_execute(query); let response = create_and_execute(query.into());
assert!(response.is_err()); assert!(response.is_err());
@ -206,10 +205,10 @@ fn can_access_context() {
humanWithContext { humanWithContext {
id 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 mut iterator_count = 0;
let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn(
@ -234,10 +233,10 @@ fn resolves_typed_inline_fragments() {
id 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 mut iterator_count = 0;
let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn(
@ -262,10 +261,10 @@ fn resolves_nontyped_inline_fragments() {
id 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 mut iterator_count = 0;
let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn(
@ -289,10 +288,10 @@ fn can_access_arguments() {
id id
name 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 mut iterator_count = 0;
let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn(
@ -317,10 +316,10 @@ fn type_alias() {
id id
name 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 mut iterator_count = 0;
let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn(

View file

@ -75,15 +75,15 @@ fn test_node() {
baz baz
}"#; }"#;
let node_info = NodeTypeInfo { let node_info = NodeTypeInfo {
name: "MyNode".to_string(), name: "MyNode".into(),
attribute_names: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()], attribute_names: vec!["foo".into(), "bar".into(), "baz".into()],
}; };
let mut node = Node { let mut node = Node {
attributes: IndexMap::new(), attributes: IndexMap::new(),
}; };
node.attributes.insert("foo".to_string(), "1".to_string()); node.attributes.insert("foo".into(), "1".into());
node.attributes.insert("bar".to_string(), "2".to_string()); node.attributes.insert("bar".into(), "2".into());
node.attributes.insert("baz".to_string(), "3".to_string()); node.attributes.insert("baz".into(), "3".into());
let schema: RootNode<_, _, _> = RootNode::new_with_info( let schema: RootNode<_, _, _> = RootNode::new_with_info(
node, node,
EmptyMutation::new(), EmptyMutation::new(),

View file

@ -226,7 +226,7 @@ where
panic!( panic!(
"Field {} not found on type {:?}", "Field {} not found on type {:?}",
f.name.item, f.name.item,
meta_type.name() meta_type.name(),
) )
}); });

View file

@ -377,7 +377,7 @@ where
/// // schema in `meta()` above, or a validation failed because of a this library bug. /// // 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. /// // 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!( panic!(
"Field {} not found on type {:?}", "Field {} not found on type {:?}",
f.name.item, f.name.item,
meta_type.name() meta_type.name(),
) )
}); });

View file

@ -522,12 +522,11 @@ where
fn into_field_error(self) -> FieldError<S> { fn into_field_error(self) -> FieldError<S> {
const ERROR_PREFIX: &str = "Failed to convert into exact-size array"; const ERROR_PREFIX: &str = "Failed to convert into exact-size array";
match self { match self {
Self::Null => format!("{}: Value cannot be `null`", ERROR_PREFIX).into(), Self::Null => format!("{ERROR_PREFIX}: Value cannot be `null`").into(),
Self::WrongCount { actual, expected } => format!( Self::WrongCount { actual, expected } => {
"{}: wrong elements count: {} instead of {}", format!("{ERROR_PREFIX}: wrong elements count: {actual} instead of {expected}",)
ERROR_PREFIX, actual, expected .into()
) }
.into(),
Self::Item(s) => s.into_field_error(), Self::Item(s) => s.into_field_error(),
} }
} }

View file

@ -50,11 +50,10 @@ impl FromStr for Name {
type Err = NameParseError; type Err = NameParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
if Name::is_valid(s) { if Name::is_valid(s) {
Ok(Name(s.to_string())) Ok(Name(s.into()))
} else { } else {
Err(NameParseError(format!( Err(NameParseError(format!(
"Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{s}\" does not",
s
))) )))
} }
} }

View file

@ -32,12 +32,16 @@ use crate::{
pub enum Nullable<T> { pub enum Nullable<T> {
/// No value /// No value
ImplicitNull, ImplicitNull,
/// No value, explicitly specified to be null /// No value, explicitly specified to be null
ExplicitNull, ExplicitNull,
/// Some value `T` /// Some value `T`
Some(T), Some(T),
} }
// Implemented manually to omit redundant `T: Default` trait bound, imposed by
// `#[derive(Default)]`.
impl<T> Default for Nullable<T> { impl<T> Default for Nullable<T> {
fn default() -> Self { fn default() -> Self {
Self::ImplicitNull Self::ImplicitNull

View file

@ -37,7 +37,7 @@ impl ID {
.map(str::to_owned) .map(str::to_owned)
.or_else(|| v.as_int_value().as_ref().map(ToString::to_string)) .or_else(|| v.as_int_value().as_ref().map(ToString::to_string))
.map(Self) .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<S: ScalarValue>(v: &InputValue<S>) -> Result<String, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<String, String> {
v.as_string_value() v.as_string_value()
.map(str::to_owned) .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<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> { pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
@ -120,7 +120,7 @@ mod impl_string_scalar {
} }
Some(s) => { Some(s) => {
return Err(ParseError::LexerError(LexerError::UnknownEscapeSequence( return Err(ParseError::LexerError(LexerError::UnknownEscapeSequence(
format!("\\{}", s), format!("\\{s}"),
))) )))
} }
None => return Err(ParseError::LexerError(LexerError::UnterminatedString)), None => return Err(ParseError::LexerError(LexerError::UnterminatedString)),
@ -149,19 +149,16 @@ where
.and_then(|c1| { .and_then(|c1| {
char_iter char_iter
.next() .next()
.map(|c2| format!("{}{}", c1, c2)) .map(|c2| format!("{c1}{c2}"))
.ok_or_else(|| { .ok_or_else(|| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{}", c1))) ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{c1}")))
}) })
}) })
.and_then(|mut s| { .and_then(|mut s| {
char_iter char_iter
.next() .next()
.ok_or_else(|| { .ok_or_else(|| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{s}")))
"\\u{}",
s.clone()
)))
}) })
.map(|c2| { .map(|c2| {
s.push(c2); s.push(c2);
@ -172,10 +169,7 @@ where
char_iter char_iter
.next() .next()
.ok_or_else(|| { .ok_or_else(|| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{s}")))
"\\u{}",
s.clone()
)))
}) })
.map(|c2| { .map(|c2| {
s.push(c2); s.push(c2);
@ -184,14 +178,12 @@ where
})?; })?;
let code_point = u32::from_str_radix(&escaped_code_point, 16).map_err(|_| { let code_point = u32::from_str_radix(&escaped_code_point, 16).map_err(|_| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( ParseError::LexerError(LexerError::UnknownEscapeSequence(format!(
"\\u{}", "\\u{escaped_code_point}",
escaped_code_point
))) )))
})?; })?;
char::from_u32(code_point).ok_or_else(|| { char::from_u32(code_point).ok_or_else(|| {
ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( ParseError::LexerError(LexerError::UnknownEscapeSequence(format!(
"\\u{}", "\\u{escaped_code_point}",
escaped_code_point
))) )))
}) })
} }
@ -282,7 +274,7 @@ mod impl_boolean_scalar {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Boolean, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Boolean, String> {
v.as_scalar_value() v.as_scalar_value()
.and_then(ScalarValue::as_bool) .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<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> { pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
@ -303,7 +295,7 @@ mod impl_int_scalar {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Int, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Int, String> {
v.as_int_value() 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<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> { pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
@ -329,7 +321,7 @@ mod impl_float_scalar {
pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Float, String> { pub(super) fn from_input<S: ScalarValue>(v: &InputValue<S>) -> Result<Float, String> {
v.as_float_value() 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<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> { pub(super) fn parse_token<S: ScalarValue>(value: ScalarToken<'_>) -> ParseScalarResult<S> {
@ -401,8 +393,9 @@ where
{ {
} }
// Implemented manually to omit redundant `T: Default` trait bound, imposed by
// `#[derive(Default)]`.
impl<T> Default for EmptyMutation<T> { impl<T> Default for EmptyMutation<T> {
#[inline]
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }
@ -461,8 +454,9 @@ where
{ {
} }
// Implemented manually to omit redundant `T: Default` trait bound, imposed by
// `#[derive(Default)]`.
impl<T> Default for EmptySubscription<T> { impl<T> Default for EmptySubscription<T> {
#[inline]
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
} }
@ -499,8 +493,8 @@ mod tests {
#[test] #[test]
fn test_id_display() { fn test_id_display() {
let id = ID(String::from("foo")); let id = ID("foo".into());
assert_eq!(format!("{}", id), "foo"); assert_eq!(id.to_string(), "foo");
} }
#[test] #[test]
@ -508,7 +502,7 @@ mod tests {
fn parse_string(s: &str, expected: &str) { fn parse_string(s: &str, expected: &str) {
let s = let s =
<String as ParseScalarValue<DefaultScalarValue>>::from_str(ScalarToken::String(s)); <String as ParseScalarValue<DefaultScalarValue>>::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<String> = s.unwrap().into(); let s: Option<String> = s.unwrap().into();
assert!(s.is_some(), "No string returned"); assert!(s.is_some(), "No string returned");
assert_eq!(s.unwrap(), expected); assert_eq!(s.unwrap(), expected);
@ -527,7 +521,7 @@ mod tests {
#[test] #[test]
fn parse_f64_from_int() { fn parse_f64_from_int() {
for (v, expected) in &[ for (v, expected) in [
("0", 0), ("0", 0),
("128", 128), ("128", 128),
("1601942400", 1601942400), ("1601942400", 1601942400),
@ -538,14 +532,14 @@ mod tests {
assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err()); assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());
let n: Option<f64> = n.unwrap().into(); let n: Option<f64> = n.unwrap().into();
assert!(n.is_some(), "No f64 returned"); assert!(n.is_some(), "No `f64` returned");
assert_eq!(n.unwrap(), f64::from(*expected)); assert_eq!(n.unwrap(), f64::from(expected));
} }
} }
#[test] #[test]
fn parse_f64_from_float() { fn parse_f64_from_float() {
for (v, expected) in &[ for (v, expected) in [
("0.", 0.), ("0.", 0.),
("1.2", 1.2), ("1.2", 1.2),
("1601942400.", 1601942400.), ("1601942400.", 1601942400.),
@ -556,8 +550,8 @@ mod tests {
assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err()); assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err());
let n: Option<f64> = n.unwrap().into(); let n: Option<f64> = n.unwrap().into();
assert!(n.is_some(), "No f64 returned"); assert!(n.is_some(), "No `f64` returned");
assert_eq!(n.unwrap(), *expected); assert_eq!(n.unwrap(), expected);
} }
} }

View file

@ -30,9 +30,9 @@ pub struct ValidatorContext<'a, S: Debug + 'a> {
impl RuleError { impl RuleError {
#[doc(hidden)] #[doc(hidden)]
pub fn new(message: &str, locations: &[SourcePosition]) -> RuleError { pub fn new(message: &str, locations: &[SourcePosition]) -> Self {
RuleError { Self {
message: message.to_owned(), message: message.into(),
locations: locations.to_vec(), locations: locations.to_vec(),
} }
} }
@ -53,14 +53,15 @@ impl RuleError {
impl fmt::Display for RuleError { impl fmt::Display for RuleError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 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 let locations = self
.locations .locations
.iter() .iter()
.map(|location| format!("{}", location)) .map(ToString::to_string)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
write!(f, "{}. At {}", self.message, locations) write!(f, "{}. At {locations}", self.message)
} }
} }

View file

@ -99,7 +99,7 @@ where
var_name, var_name,
var_pos, var_pos,
&path, &path,
&format!(r#"Expected "{}", found null"#, meta_type), format!(r#"Expected "{meta_type}", found null"#),
)); ));
} else { } else {
errors.append(&mut unify_value( errors.append(&mut unify_value(
@ -121,10 +121,10 @@ where
var_name, var_name,
var_pos, var_pos,
&path, &path,
&format!( format!(
"Expected list of {} elements, found {} elements", "Expected list of {expected} elements, \
expected, found {} elements",
l.len() l.len(),
), ),
)); ));
} }
@ -168,11 +168,11 @@ where
var_name, var_name,
var_pos, var_pos,
&path, &path,
&format!( format!(
"Expected input of type `{}`. Got: `{}`. \ "Expected input of type `{}`. \
Got: `{value}`. \
Details: {}", Details: {}",
iom.name, iom.name,
value,
e.message(), e.message(),
), ),
)); ));
@ -205,10 +205,9 @@ where
var_name, var_name,
var_pos, var_pos,
path, path,
&format!( format!(
"Expected input scalar `{}`. Got: `{}`. Details: {}", "Expected input scalar `{}`. Got: `{value}`. Details: {}",
meta.name, meta.name,
value,
e.message(), e.message(),
), ),
)]; )];
@ -219,13 +218,13 @@ where
var_name, var_name,
var_pos, var_pos,
path, path,
&format!(r#"Expected "{}", found list"#, meta.name), format!(r#"Expected "{}", found list"#, meta.name),
)), )),
InputValue::Object(_) => errors.push(unification_error( InputValue::Object(_) => errors.push(unification_error(
var_name, var_name,
var_pos, var_pos,
path, path,
&format!(r#"Expected "{}", found object"#, meta.name), format!(r#"Expected "{}", found object"#, meta.name),
)), )),
_ => (), _ => (),
} }
@ -244,27 +243,27 @@ where
{ {
let mut errors: Vec<RuleError> = vec![]; let mut errors: Vec<RuleError> = vec![];
match *value { match value {
// TODO: avoid this bad duplicate as_str() call. (value system refactor) // 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 let Some(name) = scalar.as_str() {
if !meta.values.iter().any(|ev| ev.name == *name) { if !meta.values.iter().any(|ev| ev.name == *name) {
errors.push(unification_error( errors.push(unification_error(
var_name, var_name,
var_pos, var_pos,
path, 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) { if !meta.values.iter().any(|ev| &ev.name == name) {
errors.push(unification_error( errors.push(unification_error(
var_name, var_name,
var_pos, var_pos,
path, 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_name,
var_pos, var_pos,
path, path,
&format!(r#"Expected "{}", found not a string or enum"#, meta.name), format!(r#"Expected "{}", found not a string or enum"#, meta.name),
)), )),
} }
errors errors
@ -318,7 +317,7 @@ where
var_name, var_name,
var_pos, var_pos,
&Path::ObjectField(&input_field.name, path), &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_name,
var_pos, var_pos,
path, path,
&format!(r#"Expected "{}", found not an object"#, meta.name), format!(r#"Expected "{}", found not an object"#, meta.name),
)); ));
} }
errors errors
@ -349,17 +348,14 @@ where
v.map_or(true, InputValue::is_null) v.map_or(true, InputValue::is_null)
} }
fn unification_error<'a>( fn unification_error(
var_name: &str, var_name: impl fmt::Display,
var_pos: &SourcePosition, var_pos: &SourcePosition,
path: &Path<'a>, path: &Path<'_>,
message: &str, message: impl fmt::Display,
) -> RuleError { ) -> RuleError {
RuleError::new( RuleError::new(
&format!( &format!(r#"Variable "${var_name}" got invalid value. {path}{message}."#),
r#"Variable "${}" got invalid value. {}{}."#,
var_name, path, message,
),
&[*var_pos], &[*var_pos],
) )
} }
@ -368,8 +364,8 @@ impl<'a> fmt::Display for Path<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Path::Root => write!(f, ""), Path::Root => write!(f, ""),
Path::ArrayElement(idx, prev) => write!(f, "{}In element #{}: ", prev, idx), Path::ArrayElement(idx, prev) => write!(f, "{prev}In element #{idx}: "),
Path::ObjectField(name, prev) => write!(f, r#"{}In field "{}": "#, prev, name), Path::ObjectField(name, prev) => write!(f, r#"{prev}In field "{name}": "#),
} }
} }
} }

View file

@ -1,3 +1,5 @@
use std::fmt;
use crate::{ use crate::{
ast::{Directive, Field, InputValue}, ast::{Directive, Field, InputValue},
parser::Spanning, parser::Spanning,
@ -6,13 +8,12 @@ use crate::{
validation::{ValidatorContext, Visitor}, validation::{ValidatorContext, Visitor},
value::ScalarValue, 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<Argument<'a, S>>>, current_args: Option<&'a Vec<Argument<'a, S>>>,
} }
pub fn factory<'a, S: Debug>() -> ArgumentsOfCorrectType<'a, S> { pub fn factory<'a, S: fmt::Debug>() -> ArgumentsOfCorrectType<'a, S> {
ArgumentsOfCorrectType { current_args: None } ArgumentsOfCorrectType { current_args: None }
} }
@ -59,7 +60,7 @@ where
if !is_valid_literal_value(ctx.schema, &meta_type, &arg_value.item) { if !is_valid_literal_value(ctx.schema, &meta_type, &arg_value.item) {
ctx.report_error( 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], &[arg_value.start],
); );
} }
@ -67,11 +68,8 @@ where
} }
} }
fn error_message(arg_name: &str, type_name: &str) -> String { fn error_message(arg_name: impl fmt::Display, type_name: impl fmt::Display) -> String {
format!( format!("Invalid value for argument \"{arg_name}\", expected type \"{type_name}\"",)
"Invalid value for argument \"{}\", expected type \"{}\"",
arg_name, type_name
)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,3 +1,5 @@
use std::fmt;
use crate::{ use crate::{
ast::VariableDefinition, ast::VariableDefinition,
parser::Spanning, parser::Spanning,
@ -29,7 +31,7 @@ where
{ {
if var_def.var_type.item.is_non_null() { if var_def.var_type.item.is_non_null() {
ctx.report_error( 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], &[*start],
) )
} else { } else {
@ -37,7 +39,7 @@ where
if !is_valid_literal_value(ctx.schema, &meta_type, var_value) { if !is_valid_literal_value(ctx.schema, &meta_type, var_value) {
ctx.report_error( 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], &[*start],
); );
} }
@ -46,17 +48,14 @@ where
} }
} }
fn type_error_message(arg_name: &str, type_name: &str) -> String { fn type_error_message(arg_name: impl fmt::Display, type_name: impl fmt::Display) -> String {
format!( format!("Invalid default value for argument \"{arg_name}\", expected type \"{type_name}\"")
"Invalid default value for argument \"{}\", expected type \"{}\"",
arg_name, 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!( format!(
"Argument \"{}\" has type \"{}\" and is not nullable, so it can't have a default value", "Argument \"{arg_name}\" has type \"{type_name}\" and is not nullable, \
arg_name, type_name so it can't have a default value",
) )
} }

View file

@ -69,7 +69,7 @@ where
} }
fn error_message(field: &str, type_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -59,15 +59,9 @@ where
fn error_message(fragment_name: Option<&str>, on_type: &str) -> String { fn error_message(fragment_name: Option<&str>, on_type: &str) -> String {
if let Some(name) = fragment_name { if let Some(name) = fragment_name {
format!( format!(r#"Fragment "{name}" cannot condition non composite type "{on_type}"#)
r#"Fragment "{}" cannot condition non composite type "{}"#,
name, on_type
)
} else { } else {
format!( format!(r#"Fragment cannot condition on non composite type "{on_type}""#)
r#"Fragment cannot condition on non composite type "{}""#,
on_type
)
} }
} }

View file

@ -91,17 +91,11 @@ where
} }
fn field_error_message(arg_name: &str, field_name: &str, type_name: &str) -> String { fn field_error_message(arg_name: &str, field_name: &str, type_name: &str) -> String {
format!( format!(r#"Unknown argument "{arg_name}" on field "{field_name}" of type "{type_name}""#)
r#"Unknown argument "{}" on field "{}" of type "{}""#,
arg_name, field_name, type_name
)
} }
fn directive_error_message(arg_name: &str, directive_name: &str) -> String { fn directive_error_message(arg_name: &str, directive_name: &str) -> String {
format!( format!(r#"Unknown argument "{arg_name}" on directive "{directive_name}""#)
r#"Unknown argument "{}" on directive "{}""#,
arg_name, directive_name
)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -154,14 +154,11 @@ where
} }
fn unknown_error_message(directive_name: &str) -> String { 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 { fn misplaced_error_message(directive_name: &str, location: &DirectiveLocation) -> String {
format!( format!(r#"Directive "{directive_name}" may not be used on {location}"#)
r#"Directive "{}" may not be used on {}"#,
directive_name, location
)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -28,7 +28,7 @@ where
} }
fn error_message(frag_name: &str) -> String { fn error_message(frag_name: &str) -> String {
format!(r#"Unknown fragment: "{}""#, frag_name) format!(r#"Unknown fragment: "{frag_name}""#)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -56,7 +56,7 @@ fn validate_type<'a, S: Debug>(
} }
fn error_message(type_name: &str) -> String { fn error_message(type_name: &str) -> String {
format!(r#"Unknown type "{}""#, type_name) format!(r#"Unknown type "{type_name}""#)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -126,7 +126,7 @@ impl<'a> CycleDetector<'a> {
} }
fn error_message(frag_name: &str) -> String { fn error_message(frag_name: &str) -> String {
format!(r#"Cannot spread fragment "{}""#, frag_name) format!(r#"Cannot spread fragment "{frag_name}""#)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -151,12 +151,9 @@ where
fn error_message(var_name: &str, op_name: Option<&str>) -> String { fn error_message(var_name: &str, op_name: Option<&str>) -> String {
if let Some(op_name) = op_name { if let Some(op_name) = op_name {
format!( format!(r#"Variable "${var_name}" is not defined by operation "{op_name}""#)
r#"Variable "${}" is not defined by operation "{}""#,
var_name, op_name
)
} else { } else {
format!(r#"Variable "${}" is not defined"#, var_name) format!(r#"Variable "${var_name}" is not defined"#)
} }
} }

View file

@ -104,7 +104,7 @@ where
} }
fn error_message(frag_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -142,12 +142,9 @@ where
fn error_message(var_name: &str, op_name: Option<&str>) -> String { fn error_message(var_name: &str, op_name: Option<&str>) -> String {
if let Some(op_name) = op_name { if let Some(op_name) = op_name {
format!( format!(r#"Variable "${var_name}" is not used by operation "{op_name}""#)
r#"Variable "${}" is not used by operation "{}""#,
var_name, op_name
)
} else { } else {
format!(r#"Variable "${}" is not used"#, var_name) format!(r#"Variable "${var_name}" is not used"#)
} }
} }

View file

@ -376,10 +376,9 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> {
if name1 != name2 { if name1 != name2 {
return Some(Conflict( return Some(Conflict(
ConflictReason( ConflictReason(
response_name.to_owned(), response_name.into(),
ConflictReasonMessage::Message(format!( ConflictReasonMessage::Message(format!(
"{} and {} are different fields", "{name1} and {name2} are different fields",
name1, name2
)), )),
), ),
vec![ast1.start], 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) { if !self.is_same_arguments(&ast1.item.arguments, &ast2.item.arguments) {
return Some(Conflict( return Some(Conflict(
ConflictReason( ConflictReason(
response_name.to_owned(), response_name.into(),
ConflictReasonMessage::Message("they have differing arguments".to_owned()), ConflictReasonMessage::Message("they have differing arguments".into()),
), ),
vec![ast1.start], vec![ast1.start],
vec![ast2.start], vec![ast2.start],
@ -406,10 +405,9 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> {
if self.is_type_conflict(ctx, t1, t2) { if self.is_type_conflict(ctx, t1, t2) {
return Some(Conflict( return Some(Conflict(
ConflictReason( ConflictReason(
response_name.to_owned(), response_name.into(),
ConflictReasonMessage::Message(format!( ConflictReasonMessage::Message(format!(
"they return conflicting types {} and {}", "they return conflicting types {t1} and {t2}",
t1, t2
)), )),
), ),
vec![ast1.start], vec![ast1.start],
@ -513,7 +511,7 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> {
Some(Conflict( Some(Conflict(
ConflictReason( ConflictReason(
response_name.to_owned(), response_name.into(),
ConflictReasonMessage::Nested(conflicts.iter().map(|c| c.0.clone()).collect()), ConflictReasonMessage::Nested(conflicts.iter().map(|c| c.0.clone()).collect()),
), ),
vec![*pos1] vec![*pos1]
@ -722,10 +720,8 @@ where
fn error_message(reason_name: &str, reason: &ConflictReasonMessage) -> String { fn error_message(reason_name: &str, reason: &ConflictReasonMessage) -> String {
let suffix = "Use different aliases on the fields to fetch both if this was intentional"; let suffix = "Use different aliases on the fields to fetch both if this was intentional";
format!( format!(
r#"Fields "{}" conflict because {}. {}"#, r#"Fields "{reason_name}" conflict because {}. {suffix}"#,
reason_name,
format_reason(reason), format_reason(reason),
suffix
) )
} }
@ -736,9 +732,8 @@ fn format_reason(reason: &ConflictReasonMessage) -> String {
.iter() .iter()
.map(|&ConflictReason(ref name, ref subreason)| { .map(|&ConflictReason(ref name, ref subreason)| {
format!( format!(
r#"subfields "{}" conflict because {}"#, r#"subfields "{name}" conflict because {}"#,
name, format_reason(subreason),
format_reason(subreason)
) )
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
@ -872,7 +867,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"fido", "fido",
&Message("name and nickname are different fields".to_owned()), &Message("name and nickname are different fields".into()),
), ),
&[ &[
SourcePosition::new(78, 2, 12), SourcePosition::new(78, 2, 12),
@ -912,7 +907,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"name", "name",
&Message("nickname and name are different fields".to_owned()), &Message("nickname and name are different fields".into()),
), ),
&[ &[
SourcePosition::new(71, 2, 12), SourcePosition::new(71, 2, 12),
@ -935,7 +930,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"doesKnowCommand", "doesKnowCommand",
&Message("they have differing arguments".to_owned()), &Message("they have differing arguments".into()),
), ),
&[ &[
SourcePosition::new(57, 2, 12), SourcePosition::new(57, 2, 12),
@ -958,7 +953,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"doesKnowCommand", "doesKnowCommand",
&Message("they have differing arguments".to_owned()), &Message("they have differing arguments".into()),
), ),
&[ &[
SourcePosition::new(57, 2, 12), SourcePosition::new(57, 2, 12),
@ -981,7 +976,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"doesKnowCommand", "doesKnowCommand",
&Message("they have differing arguments".to_owned()), &Message("they have differing arguments".into()),
), ),
&[ &[
SourcePosition::new(57, 2, 12), SourcePosition::new(57, 2, 12),
@ -1025,10 +1020,7 @@ mod tests {
} }
"#, "#,
&[RuleError::new( &[RuleError::new(
&error_message( &error_message("x", &Message("name and barks are different fields".into())),
"x",
&Message("name and barks are different fields".to_owned()),
),
&[ &[
SourcePosition::new(101, 6, 12), SourcePosition::new(101, 6, 12),
SourcePosition::new(163, 9, 12), SourcePosition::new(163, 9, 12),
@ -1066,10 +1058,7 @@ mod tests {
"#, "#,
&[ &[
RuleError::new( RuleError::new(
&error_message( &error_message("x", &Message("name and barks are different fields".into())),
"x",
&Message("name and barks are different fields".to_owned()),
),
&[ &[
SourcePosition::new(235, 13, 14), SourcePosition::new(235, 13, 14),
SourcePosition::new(311, 17, 12), SourcePosition::new(311, 17, 12),
@ -1078,7 +1067,7 @@ mod tests {
RuleError::new( RuleError::new(
&error_message( &error_message(
"x", "x",
&Message("name and nickname are different fields".to_owned()), &Message("name and nickname are different fields".into()),
), ),
&[ &[
SourcePosition::new(235, 13, 14), SourcePosition::new(235, 13, 14),
@ -1088,7 +1077,7 @@ mod tests {
RuleError::new( RuleError::new(
&error_message( &error_message(
"x", "x",
&Message("barks and nickname are different fields".to_owned()), &Message("barks and nickname are different fields".into()),
), ),
&[ &[
SourcePosition::new(311, 17, 12), SourcePosition::new(311, 17, 12),
@ -1117,8 +1106,8 @@ mod tests {
&error_message( &error_message(
"dog", "dog",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"x".to_owned(), "x".into(),
Message("name and barks are different fields".to_owned()), Message("name and barks are different fields".into()),
)]), )]),
), ),
&[ &[
@ -1152,12 +1141,12 @@ mod tests {
"dog", "dog",
&Nested(vec![ &Nested(vec![
ConflictReason( ConflictReason(
"x".to_owned(), "x".into(),
Message("barks and nickname are different fields".to_owned()), Message("barks and nickname are different fields".into()),
), ),
ConflictReason( ConflictReason(
"y".to_owned(), "y".into(),
Message("name and barkVolume are different fields".to_owned()), Message("name and barkVolume are different fields".into()),
), ),
]), ]),
), ),
@ -1195,10 +1184,10 @@ mod tests {
&error_message( &error_message(
"human", "human",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"relatives".to_owned(), "relatives".into(),
Nested(vec![ConflictReason( Nested(vec![ConflictReason(
"x".to_owned(), "x".into(),
Message("name and iq are different fields".to_owned()), Message("name and iq are different fields".into()),
)]), )]),
)]), )]),
), ),
@ -1239,8 +1228,8 @@ mod tests {
&error_message( &error_message(
"relatives", "relatives",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"x".to_owned(), "x".into(),
Message("iq and name are different fields".to_owned()), Message("iq and name are different fields".into()),
)]), )]),
), ),
&[ &[
@ -1286,8 +1275,8 @@ mod tests {
&error_message( &error_message(
"relatives", "relatives",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"x".to_owned(), "x".into(),
Message("iq and name are different fields".to_owned()), Message("iq and name are different fields".into()),
)]), )]),
), ),
&[ &[
@ -1333,12 +1322,12 @@ mod tests {
"dog", "dog",
&Nested(vec![ &Nested(vec![
ConflictReason( ConflictReason(
"x".to_owned(), "x".into(),
Message("name and barks are different fields".to_owned()), Message("name and barks are different fields".into()),
), ),
ConflictReason( ConflictReason(
"y".to_owned(), "y".into(),
Message("barkVolume and nickname are different fields".to_owned()), Message("barkVolume and nickname are different fields".into()),
), ),
]), ]),
), ),
@ -1794,7 +1783,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"scalar", "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), SourcePosition::new(88, 4, 18),
@ -1858,7 +1847,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"scalar", "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), SourcePosition::new(89, 4, 18),
@ -1922,8 +1911,8 @@ mod tests {
&error_message( &error_message(
"other", "other",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"otherField".to_owned(), "otherField".into(),
Message("otherField and unrelatedField are different fields".to_owned()), Message("otherField and unrelatedField are different fields".into()),
)]), )]),
), ),
&[ &[
@ -1957,7 +1946,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"scalar", "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), SourcePosition::new(100, 4, 18),
@ -1992,7 +1981,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"box", "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), SourcePosition::new(89, 4, 18),
@ -2024,7 +2013,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"box", "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), SourcePosition::new(89, 4, 18),
@ -2060,7 +2049,7 @@ mod tests {
&[RuleError::new( &[RuleError::new(
&error_message( &error_message(
"val", "val",
&Message("scalar and unrelatedField are different fields".to_owned()), &Message("scalar and unrelatedField are different fields".into()),
), ),
&[ &[
SourcePosition::new(126, 5, 20), SourcePosition::new(126, 5, 20),
@ -2096,8 +2085,8 @@ mod tests {
&error_message( &error_message(
"box", "box",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"scalar".to_owned(), "scalar".into(),
Message("they return conflicting types String and Int".to_owned()), Message("they return conflicting types String and Int".into()),
)]), )]),
), ),
&[ &[
@ -2227,10 +2216,10 @@ mod tests {
&error_message( &error_message(
"edges", "edges",
&Nested(vec![ConflictReason( &Nested(vec![ConflictReason(
"node".to_owned(), "node".into(),
Nested(vec![ConflictReason( Nested(vec![ConflictReason(
"id".to_owned(), "id".into(),
Message("name and id are different fields".to_owned()), Message("name and id are different fields".into()),
)]), )]),
)]), )]),
), ),
@ -2278,7 +2267,7 @@ mod tests {
#[test] #[test]
fn error_message_contains_hint_for_alias_conflict() { fn error_message_contains_hint_for_alias_conflict() {
assert_eq!( 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 \ "Fields \"x\" conflict because a and b are different fields. Use \
different aliases on the fields to fetch both if this \ different aliases on the fields to fetch both if this \
was intentional" was intentional"

View file

@ -119,15 +119,13 @@ where
fn error_message(frag_name: Option<&str>, parent_type_name: &str, frag_type: &str) -> String { fn error_message(frag_name: Option<&str>, parent_type_name: &str, frag_type: &str) -> String {
if let Some(frag_name) = frag_name { if let Some(frag_name) = frag_name {
format!( format!(
"Fragment \"{}\" cannot be spread here as objects of type \ "Fragment \"{frag_name}\" cannot be spread here as objects of type \
\"{}\" can never be of type \"{}\"", \"{parent_type_name}\" can never be of type \"{frag_type}\"",
frag_name, parent_type_name, frag_type
) )
} else { } else {
format!( format!(
"Fragment cannot be spread here as objects of type \"{}\" \ "Fragment cannot be spread here as objects of type \
can never be of type \"{}\"", \"{parent_type_name}\" can never be of type \"{frag_type}\"",
parent_type_name, frag_type
) )
} }
} }

View file

@ -1,3 +1,5 @@
use std::fmt;
use crate::{ use crate::{
ast::{Directive, Field}, ast::{Directive, Field},
parser::Spanning, parser::Spanning,
@ -35,11 +37,7 @@ where
.is_none() .is_none()
{ {
ctx.report_error( ctx.report_error(
&field_error_message( &field_error_message(field_name, &meta_arg.name, &meta_arg.arg_type),
field_name,
&meta_arg.name,
&format!("{}", meta_arg.arg_type),
),
&[field.start], &[field.start],
); );
} }
@ -72,7 +70,7 @@ where
&directive_error_message( &directive_error_message(
directive_name, directive_name,
&meta_arg.name, &meta_arg.name,
&format!("{}", meta_arg.arg_type), &meta_arg.arg_type,
), ),
&[directive.start], &[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!( format!(
r#"Field "{}" argument "{}" of type "{}" is required but not provided"#, r#"Field "{field_name}" argument "{arg_name}" of type "{type_name}" is required but not provided"#,
field_name, arg_name, type_name
) )
} }
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!( format!(
r#"Directive "@{}" argument "{}" of type "{}" is required but not provided"#, r#"Directive "@{directive_name}" argument "{arg_name}" of type "{type_name}" is required but not provided"#,
directive_name, arg_name, type_name
) )
} }

View file

@ -1,3 +1,5 @@
use std::fmt;
use crate::{ use crate::{
ast::Field, ast::Field,
parser::Spanning, parser::Spanning,
@ -23,11 +25,11 @@ where
{ {
match (field_type.is_leaf(), &field.item.selection_set) { match (field_type.is_leaf(), &field.item.selection_set) {
(true, &Some(_)) => Some(RuleError::new( (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], &[field.start],
)), )),
(false, &None) => Some(RuleError::new( (false, &None) => Some(RuleError::new(
&required_error_message(field_name, &format!("{}", field_type_literal)), &required_error_message(field_name, field_type_literal),
&[field.start], &[field.start],
)), )),
_ => None, _ => 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!( format!(
r#"Field "{}" must not have a selection since type {} has no subfields"#, r#"Field "{field_name}" must not have a selection since type {type_name} has no subfields"#,
field_name, type_name
) )
} }
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!( format!(
r#"Field "{}" of type "{}" must have a selection of subfields. Did you mean "{} {{ ... }}"?"#, r#"Field "{field_name}" of type "{type_name}" must have a selection of subfields. Did you mean "{field_name} {{ ... }}"?"#,
field_name, type_name, field_name
) )
} }

View file

@ -46,7 +46,7 @@ where
} }
fn error_message(arg_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -41,7 +41,7 @@ where
} }
fn duplicate_message(frag_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -53,7 +53,7 @@ where
type SpannedObject<'a, S> = Spanning<&'a Vec<(Spanning<String>, Spanning<InputValue<S>>)>>; type SpannedObject<'a, S> = Spanning<&'a Vec<(Spanning<String>, Spanning<InputValue<S>>)>>;
fn error_message(field_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -40,7 +40,7 @@ where
} }
fn error_message(op_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -46,7 +46,7 @@ where
} }
fn error_message(var_name: &str) -> String { 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)] #[cfg(test)]

View file

@ -1,3 +1,5 @@
use std::fmt;
use crate::{ use crate::{
ast::VariableDefinition, ast::VariableDefinition,
parser::Spanning, parser::Spanning,
@ -26,7 +28,7 @@ where
{ {
if !var_type.is_input() { if !var_type.is_input() {
ctx.report_error( 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], &[var_def.var_type.start],
); );
} }
@ -34,11 +36,8 @@ where
} }
} }
fn error_message(var_name: &str, type_name: &str) -> String { fn error_message(var_name: impl fmt::Display, type_name: impl fmt::Display) -> String {
format!( format!("Variable \"{var_name}\" cannot be of non-input type \"{type_name}\"")
"Variable \"{}\" cannot be of non-input type \"{}\"",
var_name, type_name
)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,7 +1,7 @@
use std::{ use std::{
borrow::Cow, borrow::Cow,
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
fmt::Debug, fmt,
}; };
use crate::{ use crate::{
@ -17,7 +17,7 @@ pub enum Scope<'a> {
Fragment(&'a str), Fragment(&'a str),
} }
pub struct VariableInAllowedPosition<'a, S: Debug + 'a> { pub struct VariableInAllowedPosition<'a, S: fmt::Debug + 'a> {
spreads: HashMap<Scope<'a>, HashSet<&'a str>>, spreads: HashMap<Scope<'a>, HashSet<&'a str>>,
variable_usages: HashMap<Scope<'a>, Vec<(Spanning<&'a String>, Type<'a>)>>, variable_usages: HashMap<Scope<'a>, Vec<(Spanning<&'a String>, Type<'a>)>>,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
@ -25,7 +25,7 @@ pub struct VariableInAllowedPosition<'a, S: Debug + 'a> {
current_scope: Option<Scope<'a>>, current_scope: Option<Scope<'a>>,
} }
pub fn factory<'a, S: Debug>() -> VariableInAllowedPosition<'a, S> { pub fn factory<'a, S: fmt::Debug>() -> VariableInAllowedPosition<'a, S> {
VariableInAllowedPosition { VariableInAllowedPosition {
spreads: HashMap::new(), spreads: HashMap::new(),
variable_usages: 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( fn collect_incorrect_usages(
&self, &self,
from: &Scope<'a>, from: &Scope<'a>,
@ -66,11 +66,7 @@ impl<'a, S: Debug> VariableInAllowedPosition<'a, S> {
if !ctx.schema.is_subtype(&expected_type, var_type) { if !ctx.schema.is_subtype(&expected_type, var_type) {
ctx.report_error( ctx.report_error(
&error_message( &error_message(var_name.item, expected_type, var_type),
var_name.item,
&format!("{}", expected_type),
&format!("{}", var_type),
),
&[var_def_name.start, var_name.start], &[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!( format!(
"Variable \"{}\" of type \"{}\" used in position expecting type \"{}\"", "Variable \"{var_name}\" of type \"{type_name}\" used in position expecting type \"{expected_type_name}\"",
var_name, type_name, expected_type_name
) )
} }

View file

@ -920,7 +920,7 @@ where
)); ));
let doc = 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); let mut ctx = ValidatorContext::new(unsafe { mem::transmute(&root.schema) }, &doc);
visit_fn(&mut ctx, unsafe { mem::transmute(doc.as_slice()) }); visit_fn(&mut ctx, unsafe { mem::transmute(doc.as_slice()) });

View file

@ -196,15 +196,15 @@ impl<S: ScalarValue> fmt::Display for Value<S> {
Self::Null => write!(f, "null"), Self::Null => write!(f, "null"),
Self::Scalar(s) => { Self::Scalar(s) => {
if let Some(string) = s.as_string() { if let Some(string) = s.as_string() {
write!(f, "\"{}\"", string) write!(f, "\"{string}\"")
} else { } else {
write!(f, "{}", s) write!(f, "{s}")
} }
} }
Self::List(list) => { Self::List(list) => {
write!(f, "[")?; write!(f, "[")?;
for (idx, item) in list.iter().enumerate() { for (idx, item) in list.iter().enumerate() {
write!(f, "{}", item)?; write!(f, "{item}")?;
if idx < list.len() - 1 { if idx < list.len() - 1 {
write!(f, ", ")?; write!(f, ", ")?;
} }
@ -216,7 +216,7 @@ impl<S: ScalarValue> fmt::Display for Value<S> {
Self::Object(obj) => { Self::Object(obj) => {
write!(f, "{{")?; write!(f, "{{")?;
for (idx, (key, value)) in obj.iter().enumerate() { for (idx, (key, value)) in obj.iter().enumerate() {
write!(f, "\"{}\": {}", key, value)?; write!(f, "\"{key}\": {value}")?;
if idx < obj.field_count() - 1 { if idx < obj.field_count() - 1 {
write!(f, ", ")?; write!(f, ", ")?;
@ -287,52 +287,52 @@ mod tests {
#[test] #[test]
fn display_null() { fn display_null() {
let s: Value = graphql_value!(null); let s: Value = graphql_value!(null);
assert_eq!("null", format!("{}", s)); assert_eq!(s.to_string(), "null");
} }
#[test] #[test]
fn display_int() { fn display_int() {
let s: Value = graphql_value!(123); let s: Value = graphql_value!(123);
assert_eq!("123", format!("{}", s)); assert_eq!(s.to_string(), "123");
} }
#[test] #[test]
fn display_float() { fn display_float() {
let s: Value = graphql_value!(123.456); let s: Value = graphql_value!(123.456);
assert_eq!("123.456", format!("{}", s)); assert_eq!(s.to_string(), "123.456");
} }
#[test] #[test]
fn display_string() { fn display_string() {
let s: Value = graphql_value!("foo"); let s: Value = graphql_value!("foo");
assert_eq!("\"foo\"", format!("{}", s)); assert_eq!(s.to_string(), "\"foo\"");
} }
#[test] #[test]
fn display_bool() { fn display_bool() {
let s: Value = graphql_value!(false); let s: Value = graphql_value!(false);
assert_eq!("false", format!("{}", s)); assert_eq!(s.to_string(), "false");
let s: Value = graphql_value!(true); let s: Value = graphql_value!(true);
assert_eq!("true", format!("{}", s)); assert_eq!(s.to_string(), "true");
} }
#[test] #[test]
fn display_list() { fn display_list() {
let s: Value = graphql_value!([1, null, "foo"]); let s: Value = graphql_value!([1, null, "foo"]);
assert_eq!("[1, null, \"foo\"]", format!("{}", s)); assert_eq!(s.to_string(), "[1, null, \"foo\"]");
} }
#[test] #[test]
fn display_list_one_element() { fn display_list_one_element() {
let s: Value = graphql_value!([1]); let s: Value = graphql_value!([1]);
assert_eq!("[1]", format!("{}", s)); assert_eq!(s.to_string(), "[1]");
} }
#[test] #[test]
fn display_list_empty() { fn display_list_empty() {
let s: Value = graphql_value!([]); let s: Value = graphql_value!([]);
assert_eq!("[]", format!("{}", s)); assert_eq!(s.to_string(), "[]");
} }
#[test] #[test]
@ -343,8 +343,8 @@ mod tests {
"string": "foo", "string": "foo",
}); });
assert_eq!( assert_eq!(
s.to_string(),
r#"{"int": 1, "null": null, "string": "foo"}"#, r#"{"int": 1, "null": null, "string": "foo"}"#,
format!("{}", s)
); );
} }
@ -353,12 +353,12 @@ mod tests {
let s: Value = graphql_value!({ let s: Value = graphql_value!({
"int": 1, "int": 1,
}); });
assert_eq!(r#"{"int": 1}"#, format!("{}", s)); assert_eq!(s.to_string(), r#"{"int": 1}"#);
} }
#[test] #[test]
fn display_object_empty() { fn display_object_empty() {
let s: Value = graphql_value!({}); let s: Value = graphql_value!({});
assert_eq!(r#"{}"#, format!("{}", s)); assert_eq!(s.to_string(), r#"{}"#);
} }
} }

View file

@ -1,4 +1,4 @@
use std::{iter::FromIterator, mem}; use std::mem;
use super::Value; use super::Value;
use indexmap::map::{IndexMap, IntoIter}; use indexmap::map::{IndexMap, IntoIter};

View file

@ -34,7 +34,7 @@ pub trait ParseScalarValue<S = DefaultScalarValue> {
/// integers. /// integers.
/// ///
/// ```rust /// ```rust
/// # use std::{fmt, convert::TryInto as _}; /// # use std::fmt;
/// # /// #
/// # use serde::{de, Deserialize, Deserializer, Serialize}; /// # use serde::{de, Deserialize, Deserializer, Serialize};
/// # use juniper::ScalarValue; /// # use juniper::ScalarValue;

View file

@ -1,7 +1,8 @@
[package] [package]
name = "juniper_actix" name = "juniper_actix"
version = "0.5.0-dev" version = "0.5.0-dev"
edition = "2018" edition = "2021"
rust-version = "1.62"
description = "`juniper` GraphQL integration with `actix-web`." description = "`juniper` GraphQL integration with `actix-web`."
license = "BSD-2-Clause" license = "BSD-2-Clause"
authors = ["Jordao Rosario <jordao.rosario01@gmail.com>"] authors = ["Jordao Rosario <jordao.rosario01@gmail.com>"]

View file

@ -21,7 +21,7 @@ pub struct User {
name: String, name: String,
} }
#[derive(Default, Clone)] #[derive(Clone, Default)]
pub struct Database { pub struct Database {
///this could be a database connection ///this could be a database connection
users: HashMap<i32, User>, users: HashMap<i32, User>,
@ -33,28 +33,28 @@ impl Database {
1, 1,
User { User {
id: 1, id: 1,
name: "Aron".to_string(), name: "Aron".into(),
}, },
); );
users.insert( users.insert(
2, 2,
User { User {
id: 2, id: 2,
name: "Bea".to_string(), name: "Bea".into(),
}, },
); );
users.insert( users.insert(
3, 3,
User { User {
id: 3, id: 3,
name: "Carl".to_string(), name: "Carl".into(),
}, },
); );
users.insert( users.insert(
4, 4,
User { User {
id: 4, id: 4,
name: "Dora".to_string(), name: "Dora".into(),
}, },
); );
Database { users } Database { users }

View file

@ -368,7 +368,7 @@ pub mod subscriptions {
Err(e) => { Err(e) => {
let reason = ws::CloseReason { let reason = ws::CloseReason {
code: ws::CloseCode::Error, code: ws::CloseCode::Error,
description: Some(format!("error serializing response: {}", e)), description: Some(format!("error serializing response: {e}")),
}; };
// TODO: trace // TODO: trace
@ -389,7 +389,7 @@ pub mod subscriptions {
#[derive(Debug)] #[derive(Debug)]
struct Message(ws::Message); struct Message(ws::Message);
impl<S: ScalarValue> std::convert::TryFrom<Message> for ClientMessage<S> { impl<S: ScalarValue> TryFrom<Message> for ClientMessage<S> {
type Error = Error; type Error = Error;
fn try_from(msg: Message) -> Result<Self, Self::Error> { fn try_from(msg: Message) -> Result<Self, Self::Error> {
@ -416,7 +416,7 @@ pub mod subscriptions {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Self::Serde(e) => write!(f, "serde error: {}", e), Self::Serde(e) => write!(f, "serde error: {e}"),
Self::UnexpectedClientMessage => { Self::UnexpectedClientMessage => {
write!(f, "unexpected message received from client") write!(f, "unexpected message received from client")
} }
@ -712,7 +712,7 @@ mod tests {
self.make_request( self.make_request(
TestRequest::post() TestRequest::post()
.append_header(("content-type", "application/json")) .append_header(("content-type", "application/json"))
.set_payload(body.to_string()) .set_payload(body.to_owned())
.uri(url), .uri(url),
) )
} }
@ -721,7 +721,7 @@ mod tests {
self.make_request( self.make_request(
TestRequest::post() TestRequest::post()
.append_header(("content-type", "application/graphql")) .append_header(("content-type", "application/graphql"))
.set_payload(body.to_string()) .set_payload(body.to_owned())
.uri(url), .uri(url),
) )
} }
@ -735,7 +735,7 @@ mod tests {
.unwrap() .unwrap()
.to_str() .to_str()
.unwrap() .unwrap()
.to_string(); .into();
let body = take_response_body_string(resp).await; let body = take_response_body_string(resp).await;
TestResponse { TestResponse {
status_code: status_code as i32, status_code: status_code as i32,
@ -797,29 +797,28 @@ mod subscription_tests {
framed framed
.send(ws::Message::Text(body.to_owned().into())) .send(ws::Message::Text(body.to_owned().into()))
.await .await
.map_err(|e| anyhow::anyhow!("WS error: {:?}", e))?; .map_err(|e| anyhow::anyhow!("WS error: {e:?}"))?;
} }
WsIntegrationMessage::Expect(body, message_timeout) => { WsIntegrationMessage::Expect(body, message_timeout) => {
let frame = timeout(Duration::from_millis(*message_timeout), framed.next()) let frame = timeout(Duration::from_millis(*message_timeout), framed.next())
.await .await
.map_err(|_| anyhow::anyhow!("Timed-out waiting for message"))? .map_err(|_| anyhow::anyhow!("Timed-out waiting for message"))?
.ok_or_else(|| anyhow::anyhow!("Empty message received"))? .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 { match frame {
ws::Frame::Text(ref bytes) => { ws::Frame::Text(ref bytes) => {
let expected_value = let expected_value =
serde_json::from_str::<serde_json::Value>(body) serde_json::from_str::<serde_json::Value>(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) 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 { if value != expected_value {
return Err(anyhow::anyhow!( return Err(anyhow::anyhow!(
"Expected message: {}. Received message: {}", "Expected message: {expected_value}. \
expected_value, Received message: {value}",
value,
)); ));
} }
} }

View file

@ -1,7 +1,8 @@
[package] [package]
name = "juniper_codegen" name = "juniper_codegen"
version = "0.16.0-dev" version = "0.16.0-dev"
edition = "2018" edition = "2021"
rust-version = "1.62"
description = "Code generation for `juniper` crate." description = "Code generation for `juniper` crate."
license = "BSD-2-Clause" license = "BSD-2-Clause"
authors = [ authors = [

View file

@ -15,9 +15,10 @@ use crate::common::parse::ParseBufferExt as _;
/// Representation of a [GraphQL default value][0] for code generation. /// Representation of a [GraphQL default value][0] for code generation.
/// ///
/// [0]: https://spec.graphql.org/October2021#DefaultValue /// [0]: https://spec.graphql.org/October2021#DefaultValue
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub(crate) enum Value { pub(crate) enum Value {
/// [`Default`] implementation should be used. /// [`Default`] implementation should be used.
#[default]
Default, Default,
/// Explicit [`Expr`]ession to be used as the [default value][0]. /// Explicit [`Expr`]ession to be used as the [default value][0].
@ -27,12 +28,6 @@ pub(crate) enum Value {
Expr(Box<syn::Expr>), Expr(Box<syn::Expr>),
} }
impl Default for Value {
fn default() -> Self {
Self::Default
}
}
impl From<Option<syn::Expr>> for Value { impl From<Option<syn::Expr>> for Value {
fn from(opt: Option<syn::Expr>) -> Self { fn from(opt: Option<syn::Expr>) -> Self {
match opt { match opt {

Some files were not shown because too many files have changed in this diff Show more