Remove internal versions of proc macros (#687)

- generate always `::juniper::` crate path in proc macros and use `extern crate self` to make it work inside `juniper`
- add optional non-documented `internal` proc macro argument to proc macros, which allows double-underscored names and is used inside `juniper` only
This commit is contained in:
Kai Ren 2020-06-30 12:26:48 +03:00 committed by GitHub
parent 35b804c37b
commit 7578175baf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
43 changed files with 496 additions and 759 deletions

View file

@ -1,6 +1,6 @@
use crate::{EmptyMutation, RootNode, Value};
#[derive(crate::GraphQLEnumInternal)]
#[derive(crate::GraphQLEnum)]
enum UserKind {
Admin,
User,
@ -14,7 +14,7 @@ struct User {
kind: UserKind,
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl User {
async fn id(&self) -> i32 {
self.id
@ -46,7 +46,7 @@ impl User {
struct Query;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Query {
fn field_sync(&self) -> &'static str {
"field_sync"

View file

@ -7,7 +7,7 @@ use crate::{
struct TestType;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl TestType {
fn a() -> &str {
"a"

View file

@ -1,5 +1,3 @@
use juniper_codegen::GraphQLEnumInternal as GraphQLEnum;
use crate::{
ast::InputValue,
executor::Variables,
@ -8,6 +6,7 @@ use crate::{
types::scalars::{EmptyMutation, EmptySubscription},
validation::RuleError,
value::{DefaultScalarValue, Object, Value},
GraphQLEnum,
GraphQLError::ValidationError,
};
@ -19,7 +18,7 @@ enum Color {
}
struct TestType;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl TestType {
fn to_string(color: Color) -> String {
format!("Color::{:?}", color)

View file

@ -9,7 +9,7 @@ mod field_execution {
struct DataType;
struct DeepDataType;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl DataType {
fn a() -> &str {
"Apple"
@ -39,7 +39,7 @@ mod field_execution {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl DeepDataType {
fn a() -> &str {
"Already Been Done"
@ -170,7 +170,7 @@ mod merge_parallel_fragments {
struct Type;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Type {
fn a() -> &str {
"Apple"
@ -261,7 +261,7 @@ mod merge_parallel_inline_fragments {
struct Type;
struct Other;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Type {
fn a() -> &str {
"Apple"
@ -280,7 +280,7 @@ mod merge_parallel_inline_fragments {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Other {
fn a() -> &str {
"Apple"
@ -418,7 +418,7 @@ mod threads_context_correctly {
impl Context for TestContext {}
#[crate::graphql_object_internal(
#[crate::graphql_object(
Context = TestContext,
)]
impl Schema {
@ -491,7 +491,7 @@ mod dynamic_context_switching {
struct ItemRef;
#[crate::graphql_object_internal(Context = OuterContext)]
#[crate::graphql_object(Context = OuterContext)]
impl Schema {
fn item_opt(_context: &OuterContext, key: i32) -> Option<(&InnerContext, ItemRef)> {
executor.context().items.get(&key).map(|c| (c, ItemRef))
@ -521,7 +521,7 @@ mod dynamic_context_switching {
}
}
#[crate::graphql_object_internal(Context = InnerContext)]
#[crate::graphql_object(Context = InnerContext)]
impl ItemRef {
fn value(context: &InnerContext) -> String {
context.value.clone()
@ -857,7 +857,7 @@ mod propagates_errors_to_nullable_fields {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Schema {
fn inner() -> Inner {
Inner
@ -870,7 +870,7 @@ mod propagates_errors_to_nullable_fields {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Inner {
fn nullable_field() -> Option<Inner> {
Some(Inner)
@ -1166,7 +1166,7 @@ mod named_operations {
struct Schema;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Schema {
fn a(p: Option<String>) -> &str {
let _ = p;

View file

@ -39,7 +39,7 @@ mod interface {
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
interfaces = [&dyn Pet]
)]
impl Dog {
@ -65,7 +65,7 @@ mod interface {
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
interfaces = [&dyn Pet]
)]
impl Cat {
@ -81,7 +81,7 @@ mod interface {
pets: Vec<Box<dyn Pet>>,
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Schema {
fn pets(&self) -> Vec<&dyn Pet> {
self.pets.iter().map(|p| p.as_ref()).collect()
@ -167,7 +167,7 @@ mod union {
value::Value,
};
#[crate::graphql_union_internal]
#[crate::graphql_union]
trait Pet {
fn as_dog(&self) -> Option<&Dog> {
None
@ -188,7 +188,7 @@ mod union {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Dog {
fn name(&self) -> &str {
&self.name
@ -209,7 +209,7 @@ mod union {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Cat {
fn name(&self) -> &str {
&self.name
@ -223,7 +223,7 @@ mod union {
pets: Vec<Box<dyn Pet>>,
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Schema {
fn pets(&self) -> Vec<&dyn Pet> {
self.pets.iter().map(|p| p.as_ref()).collect()

View file

@ -1,10 +1,9 @@
use juniper_codegen::GraphQLEnumInternal as GraphQLEnum;
use crate::{
executor::Variables,
schema::model::RootNode,
types::scalars::{EmptyMutation, EmptySubscription},
value::{DefaultScalarValue, Object, Value},
GraphQLEnum,
};
/*
@ -66,7 +65,7 @@ enum EnumDeprecation {
struct Root;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Root {
fn default_name() -> DefaultName {
DefaultName::Foo

View file

@ -1,13 +1,12 @@
#![deny(unused_variables)]
use juniper_codegen::GraphQLInputObjectInternal as GraphQLInputObject;
use crate::{
ast::{FromInputValue, InputValue},
executor::Variables,
schema::model::RootNode,
types::scalars::{EmptyMutation, EmptySubscription},
value::{DefaultScalarValue, Object, Value},
GraphQLInputObject,
};
struct Root;
@ -83,7 +82,7 @@ struct FieldWithDefaults {
field_two: i32,
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Root {
fn test_field(
a1: DefaultName,

View file

@ -1,8 +1,6 @@
mod enums;
mod input_object;
use juniper_codegen::GraphQLEnumInternal as GraphQLEnum;
// This asserts that the input objects defined public actually became public
#[allow(unused_imports)]
use self::input_object::{NamedPublic, NamedPublicWithDescription};
@ -12,6 +10,7 @@ use crate::{
schema::model::RootNode,
types::scalars::{EmptyMutation, EmptySubscription},
value::{DefaultScalarValue, ParseScalarResult, ParseScalarValue, Value},
GraphQLEnum,
};
#[derive(GraphQLEnum)]
@ -27,7 +26,7 @@ struct Interface;
struct Root;
#[crate::graphql_scalar_internal(name = "SampleScalar")]
#[crate::graphql_scalar(name = "SampleScalar")]
impl GraphQLScalar for Scalar {
fn resolve(&self) -> Value {
Value::scalar(self.0)
@ -55,7 +54,7 @@ graphql_interface!(Interface: () as "SampleInterface" |&self| {
});
/// The root query object in the schema
#[crate::graphql_object_internal(
#[crate::graphql_object(
interfaces = [&Interface]
Scalar = crate::DefaultScalarValue,
)]

View file

@ -1,5 +1,3 @@
use juniper_codegen::GraphQLInputObjectInternal as GraphQLInputObject;
use crate::{
ast::InputValue,
executor::Variables,
@ -9,6 +7,7 @@ use crate::{
validation::RuleError,
value::{DefaultScalarValue, Object, ParseScalarResult, ParseScalarValue, Value},
GraphQLError::ValidationError,
GraphQLInputObject,
};
#[derive(Debug)]
@ -16,7 +15,7 @@ struct TestComplexScalar;
struct TestType;
#[crate::graphql_scalar_internal]
#[crate::graphql_scalar]
impl GraphQLScalar for TestComplexScalar {
fn resolve(&self) -> Value {
Value::scalar(String::from("SerializedValue"))
@ -65,7 +64,7 @@ struct InputWithDefaults {
a: i32,
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl TestType {
fn field_with_object_input(input: Option<TestInputObject>) -> String {
format!("{:?}", input)

View file

@ -7,7 +7,7 @@ use crate::{
Value,
};
#[crate::graphql_scalar_internal(description = "ObjectId")]
#[crate::graphql_scalar(description = "ObjectId")]
impl<S> GraphQLScalar for ObjectId
where
S: ScalarValue,
@ -30,7 +30,7 @@ where
}
}
#[crate::graphql_scalar_internal(description = "UtcDateTime")]
#[crate::graphql_scalar(description = "UtcDateTime")]
impl<S> GraphQLScalar for UtcDateTime
where
S: ScalarValue,

View file

@ -27,7 +27,7 @@ use crate::{
#[doc(hidden)]
pub static RFC3339_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f%:z";
#[crate::graphql_scalar_internal(name = "DateTimeFixedOffset", description = "DateTime")]
#[crate::graphql_scalar(name = "DateTimeFixedOffset", description = "DateTime")]
impl<S> GraphQLScalar for DateTime<FixedOffset>
where
S: ScalarValue,
@ -50,7 +50,7 @@ where
}
}
#[crate::graphql_scalar_internal(name = "DateTimeUtc", description = "DateTime")]
#[crate::graphql_scalar(name = "DateTimeUtc", description = "DateTime")]
impl<S> GraphQLScalar for DateTime<Utc>
where
S: ScalarValue,
@ -78,7 +78,7 @@ where
// inherent lack of precision required for the time zone resolution.
// For serialization and deserialization uses, it is best to use
// `NaiveDate` instead."
#[crate::graphql_scalar_internal(description = "NaiveDate")]
#[crate::graphql_scalar(description = "NaiveDate")]
impl<S> GraphQLScalar for NaiveDate
where
S: ScalarValue,
@ -102,7 +102,7 @@ where
}
#[cfg(feature = "scalar-naivetime")]
#[crate::graphql_scalar_internal(description = "NaiveTime")]
#[crate::graphql_scalar(description = "NaiveTime")]
impl<S> GraphQLScalar for NaiveTime
where
S: ScalarValue,
@ -127,7 +127,7 @@ where
// JSON numbers (i.e. IEEE doubles) are not precise enough for nanosecond
// datetimes. Values will be truncated to microsecond resolution.
#[crate::graphql_scalar_internal(description = "NaiveDateTime")]
#[crate::graphql_scalar(description = "NaiveDateTime")]
impl<S> GraphQLScalar for NaiveDateTime
where
S: ScalarValue,
@ -262,7 +262,7 @@ mod integration_test {
async fn test_serialization() {
struct Root;
#[crate::graphql_object_internal]
#[crate::graphql_object]
#[cfg(feature = "scalar-naivetime")]
impl Root {
fn exampleNaiveDate() -> NaiveDate {
@ -282,7 +282,7 @@ mod integration_test {
}
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
#[cfg(not(feature = "scalar-naivetime"))]
impl Root {
fn exampleNaiveDate() -> NaiveDate {

View file

@ -5,7 +5,7 @@ use crate::{
Value,
};
#[crate::graphql_scalar_internal(description = "Url")]
#[crate::graphql_scalar(description = "Url")]
impl<S> GraphQLScalar for Url
where
S: ScalarValue,

View file

@ -8,7 +8,7 @@ use crate::{
Value,
};
#[crate::graphql_scalar_internal(description = "Uuid")]
#[crate::graphql_scalar(description = "Uuid")]
impl<S> GraphQLScalar for Uuid
where
S: ScalarValue,

View file

@ -93,6 +93,10 @@ Juniper has not reached 1.0 yet, thus some API instability should be expected.
#![doc(html_root_url = "https://docs.rs/juniper/0.14.2")]
#![warn(missing_docs)]
// Required for using `juniper_codegen` macros inside this crate to resolve absolute `::juniper`
// path correctly, without errors.
extern crate self as juniper;
use std::fmt;
#[doc(hidden)]
@ -127,14 +131,6 @@ pub use juniper_codegen::{
graphql_object, graphql_scalar, graphql_subscription, graphql_union, GraphQLEnum,
GraphQLInputObject, GraphQLObject, GraphQLScalarValue, GraphQLUnion,
};
// Internal macros are not exported,
// but declared at the root to make them easier to use.
#[allow(unused_imports)]
use juniper_codegen::{
graphql_object_internal, graphql_scalar_internal, graphql_subscription_internal,
graphql_union_internal, GraphQLEnumInternal, GraphQLInputObjectInternal,
GraphQLScalarValueInternal, GraphQLUnionInternal,
};
#[macro_use]
mod value;

View file

@ -1,12 +1,11 @@
#![allow(unused)]
use juniper_codegen::GraphQLInputObjectInternal as GraphQLInputObject;
use crate::{
executor::Variables,
schema::model::RootNode,
types::scalars::{EmptyMutation, EmptySubscription},
value::{DefaultScalarValue, Value},
GraphQLInputObject,
};
struct Root;
@ -30,7 +29,7 @@ struct Point {
x: i32,
}
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Root {
fn simple() -> i32 {
0

View file

@ -22,7 +22,7 @@ Syntax to validate:
*/
#[crate::graphql_object_internal(
#[crate::graphql_object(
interfaces = [&Interface],
)]
impl Root {

View file

@ -12,7 +12,7 @@ struct WithLifetime<'a> {
value: &'a str,
}
#[crate::graphql_object_internal(Context=Context)]
#[crate::graphql_object(Context=Context)]
impl<'a> WithLifetime<'a> {
fn value(&'a self) -> &'a str {
self.value
@ -21,7 +21,7 @@ impl<'a> WithLifetime<'a> {
struct WithContext;
#[crate::graphql_object_internal(Context=Context)]
#[crate::graphql_object(Context=Context)]
impl WithContext {
fn ctx(ctx: &Context) -> bool {
ctx.flag1
@ -33,7 +33,7 @@ struct Query {
b: bool,
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
scalar = crate::DefaultScalarValue,
name = "Query",
context = Context,
@ -115,7 +115,7 @@ impl<'a> Query {
#[derive(Default)]
struct Mutation;
#[crate::graphql_object_internal(context = Context)]
#[crate::graphql_object(context = Context)]
impl Mutation {
fn empty() -> bool {
true
@ -125,7 +125,7 @@ impl Mutation {
#[derive(Default)]
struct Subscription;
#[crate::graphql_object_internal(context = Context)]
#[crate::graphql_object(context = Context)]
impl Subscription {
fn empty() -> bool {
true

View file

@ -17,7 +17,7 @@ struct WithLifetime<'a> {
value: &'a str,
}
#[crate::graphql_object_internal(Context=Context)]
#[crate::graphql_object(Context=Context)]
impl<'a> WithLifetime<'a> {
fn value(&'a self) -> &'a str {
self.value
@ -26,7 +26,7 @@ impl<'a> WithLifetime<'a> {
struct WithContext;
#[crate::graphql_object_internal(Context=Context)]
#[crate::graphql_object(Context=Context)]
impl WithContext {
fn ctx(ctx: &Context) -> bool {
ctx.flag1
@ -36,7 +36,7 @@ impl WithContext {
#[derive(Default)]
struct Query;
#[crate::graphql_object_internal(
#[crate::graphql_object(
Context = Context,
)]
impl Query {
@ -48,7 +48,7 @@ impl Query {
#[derive(Default)]
struct Mutation;
#[crate::graphql_object_internal(context = Context)]
#[crate::graphql_object(context = Context)]
impl Mutation {
fn empty() -> bool {
true
@ -62,7 +62,7 @@ struct Subscription {
b: bool,
}
#[crate::graphql_subscription_internal(
#[crate::graphql_subscription(
scalar = crate::DefaultScalarValue,
name = "Subscription",
context = Context,

View file

@ -44,7 +44,7 @@ struct ResolversWithTrailingComma;
struct Root;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl Concrete {
fn simple() -> i32 {
0
@ -113,7 +113,7 @@ graphql_interface!(ResolversWithTrailingComma: () |&self| {
field simple() -> i32 { 0 }
});
#[crate::graphql_object_internal(
#[crate::graphql_object(
// FIXME: make async work
noasync
)]

View file

@ -14,29 +14,29 @@ use std::marker::PhantomData;
use crate::{
ast::InputValue,
graphql_object_internal,
graphql_object,
schema::model::RootNode,
types::scalars::{EmptyMutation, EmptySubscription},
value::{DefaultScalarValue, Object, Value},
GraphQLUnionInternal,
GraphQLUnion,
};
struct Concrete;
#[graphql_object_internal]
#[graphql_object]
impl Concrete {
fn simple() -> i32 {
123
}
}
#[derive(GraphQLUnionInternal)]
#[derive(GraphQLUnion)]
#[graphql(name = "ACustomNamedUnion", scalar = DefaultScalarValue)]
enum CustomName {
Concrete(Concrete),
}
#[derive(GraphQLUnionInternal)]
#[derive(GraphQLUnion)]
#[graphql(on Concrete = WithLifetime::resolve, scalar = DefaultScalarValue)]
enum WithLifetime<'a> {
#[graphql(ignore)]
@ -53,7 +53,7 @@ impl<'a> WithLifetime<'a> {
}
}
#[derive(GraphQLUnionInternal)]
#[derive(GraphQLUnion)]
#[graphql(on Concrete = WithGenerics::resolve, scalar = DefaultScalarValue)]
enum WithGenerics<T> {
#[graphql(ignore)]
@ -70,7 +70,7 @@ impl<T> WithGenerics<T> {
}
}
#[derive(GraphQLUnionInternal)]
#[derive(GraphQLUnion)]
#[graphql(description = "A description", scalar = DefaultScalarValue)]
enum DescriptionFirst {
Concrete(Concrete),
@ -79,7 +79,7 @@ enum DescriptionFirst {
struct Root;
// FIXME: make async work
#[crate::graphql_object_internal(noasync)]
#[crate::graphql_object(noasync)]
impl<'a> Root {
fn custom_name() -> CustomName {
CustomName::Concrete(Concrete)

View file

@ -155,7 +155,7 @@ fn errors() {
fn issue_427_panic_is_not_expected() {
struct QueryWithoutFloat;
#[crate::graphql_object_internal]
#[crate::graphql_object]
impl QueryWithoutFloat {
fn echo(value: String) -> String {
value

View file

@ -1,21 +1,15 @@
use indexmap::IndexMap;
use juniper_codegen::{
GraphQLEnumInternal as GraphQLEnum, GraphQLInputObjectInternal as GraphQLInputObject,
};
use crate::{
ast::{FromInputValue, InputValue, Type},
parser::{value::parse_value_literal, Lexer, Parser, SourcePosition, Spanning},
value::{DefaultScalarValue, ParseScalarValue, ScalarValue},
};
use crate::{
schema::{
meta::{Argument, EnumMeta, EnumValue, InputObjectMeta, MetaType, ScalarMeta},
model::SchemaType,
},
types::scalars::{EmptyMutation, EmptySubscription},
value::{DefaultScalarValue, ParseScalarValue, ScalarValue},
GraphQLEnum, GraphQLInputObject,
};
#[derive(GraphQLEnum)]
@ -36,7 +30,7 @@ struct Foo {
struct Query;
#[crate::graphql_object_internal(Scalar = S)]
#[crate::graphql_object(Scalar = S)]
impl<'a, S> Query
where
S: crate::ScalarValue + 'a,

View file

@ -4,14 +4,13 @@ use fnv::FnvHashMap;
#[cfg(feature = "graphql-parser-integration")]
use graphql_parser::schema::Document;
use juniper_codegen::GraphQLEnumInternal as GraphQLEnum;
use crate::{
ast::Type,
executor::{Context, Registry},
schema::meta::{Argument, InterfaceMeta, MetaType, ObjectMeta, PlaceholderMeta, UnionMeta},
types::{base::GraphQLType, name::Name},
value::{DefaultScalarValue, ScalarValue},
GraphQLEnum,
};
#[cfg(feature = "graphql-parser-integration")]
@ -75,7 +74,7 @@ pub struct DirectiveType<'a, S> {
}
#[derive(Clone, PartialEq, Eq, Debug, GraphQLEnum)]
#[graphql(name = "__DirectiveLocation")]
#[graphql(name = "__DirectiveLocation", internal)]
pub enum DirectiveLocation {
Query,
Mutation,
@ -602,7 +601,7 @@ mod test {
use crate as juniper;
use crate::{
EmptyMutation, EmptySubscription, GraphQLEnum, GraphQLInputObject, GraphQLObject,
GraphQLUnionInternal as GraphQLUnion,
GraphQLUnion,
};
#[test]

View file

@ -125,10 +125,11 @@ where
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
name = "__Schema"
Context = SchemaType<'a, S>,
Scalar = S,
internal,
// FIXME: make this redundant.
noasync,
)]
@ -167,10 +168,11 @@ where
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
name = "__Type"
Context = SchemaType<'a, S>,
Scalar = S,
internal,
// FIXME: make this redundant.
noasync,
)]
@ -300,10 +302,11 @@ where
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
name = "__Field",
Context = SchemaType<'a, S>,
Scalar = S,
internal,
// FIXME: make this redundant.
noasync,
)]
@ -339,10 +342,11 @@ where
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
name = "__InputValue",
Context = SchemaType<'a, S>,
Scalar = S,
internal,
// FIXME: make this redundant.
noasync,
)]
@ -368,9 +372,10 @@ where
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
name = "__EnumValue",
Scalar = S,
internal,
// FIXME: make this redundant.
noasync,
)]
@ -395,10 +400,11 @@ where
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
name = "__Directive",
Context = SchemaType<'a, S>,
Scalar = S,
internal,
// FIXME: make this redundant.
noasync,
)]

View file

@ -2,7 +2,7 @@
use std::collections::HashMap;
use juniper_codegen::GraphQLEnumInternal as GraphQLEnum;
use crate::GraphQLEnum;
#[derive(GraphQLEnum, Copy, Clone, Eq, PartialEq, Debug)]
pub enum Episode {

View file

@ -33,7 +33,7 @@ graphql_interface!(<'a> &'a dyn Character: Database as "Character" |&self| {
}
});
#[crate::graphql_object_internal(
#[crate::graphql_object(
Context = Database,
Scalar = crate::DefaultScalarValue,
interfaces = [&dyn Character],
@ -68,7 +68,7 @@ impl<'a> &'a dyn Human {
}
}
#[crate::graphql_object_internal(
#[crate::graphql_object(
Context = Database,
Scalar = crate::DefaultScalarValue,
interfaces = [&dyn Character],
@ -105,7 +105,7 @@ impl<'a> &'a dyn Droid {
pub struct Query;
#[crate::graphql_object_internal(
#[crate::graphql_object(
Context = Database,
Scalar = crate::DefaultScalarValue,
// FIXME: make async work

View file

@ -1,18 +1,17 @@
use std::{iter, iter::FromIterator as _, pin::Pin};
use futures::{self, StreamExt as _};
use juniper_codegen::GraphQLObjectInternal;
use crate::{
http::GraphQLRequest, Context, DefaultScalarValue, EmptyMutation, ExecutionError, FieldError,
Object, RootNode, Value,
GraphQLObject, Object, RootNode, Value,
};
#[derive(Debug, Clone)]
pub struct MyContext(i32);
impl Context for MyContext {}
#[derive(GraphQLObjectInternal)]
#[derive(GraphQLObject)]
#[graphql(description = "A humanoid creature in the Star Wars universe")]
#[derive(Clone)]
struct Human {
@ -23,7 +22,7 @@ struct Human {
struct MyQuery;
#[crate::graphql_object_internal(context = MyContext)]
#[crate::graphql_object(context = MyContext)]
impl MyQuery {
fn test(&self) -> i32 {
0 // NOTICE: does not serve a purpose
@ -43,7 +42,7 @@ type HumanStream = Pin<Box<dyn futures::Stream<Item = Human> + Send>>;
struct MySubscription;
#[crate::graphql_subscription_internal(context = MyContext)]
#[crate::graphql_subscription(context = MyContext)]
impl MySubscription {
async fn async_human() -> HumanStream {
Box::pin(futures::stream::once(async {

View file

@ -1,13 +1,12 @@
use indexmap::IndexMap;
use juniper_codegen::GraphQLEnumInternal as GraphQLEnum;
use crate::{
ast::{Directive, FromInputValue, InputValue, Selection},
executor::{ExecutionResult, Executor, Registry, Variables},
parser::Spanning,
schema::meta::{Argument, MetaType},
value::{DefaultScalarValue, Object, ScalarValue, Value},
GraphQLEnum,
};
/// GraphQL type kind
@ -15,7 +14,7 @@ use crate::{
/// The GraphQL specification defines a number of type kinds - the meta type\
/// of a type.
#[derive(Clone, Eq, PartialEq, Debug, GraphQLEnum)]
#[graphql(name = "__TypeKind")]
#[graphql(name = "__TypeKind", internal)]
pub enum TypeKind {
/// ## Scalar types
///

View file

@ -42,7 +42,7 @@ impl Deref for ID {
}
}
#[crate::graphql_scalar_internal(name = "ID")]
#[crate::graphql_scalar(name = "ID")]
impl<S> GraphQLScalar for ID
where
S: ScalarValue,
@ -69,7 +69,7 @@ where
}
}
#[crate::graphql_scalar_internal(name = "String")]
#[crate::graphql_scalar(name = "String")]
impl<S> GraphQLScalar for String
where
S: ScalarValue,
@ -258,7 +258,7 @@ where
}
}
#[crate::graphql_scalar_internal(name = "Boolean")]
#[crate::graphql_scalar(name = "Boolean")]
impl<S> GraphQLScalar for bool
where
S: ScalarValue,
@ -280,7 +280,7 @@ where
}
}
#[crate::graphql_scalar_internal(name = "Int")]
#[crate::graphql_scalar(name = "Int")]
impl<S> GraphQLScalar for i32
where
S: ScalarValue,
@ -307,7 +307,7 @@ where
}
}
#[crate::graphql_scalar_internal(name = "Float")]
#[crate::graphql_scalar(name = "Float")]
impl<S> GraphQLScalar for f64
where
S: ScalarValue,

View file

@ -1,5 +1,3 @@
use juniper_codegen::GraphQLInputObjectInternal as GraphQLInputObject;
use crate::{
ast::{FromInputValue, InputValue},
executor::Registry,
@ -14,6 +12,7 @@ use crate::{
},
validation::{visit, MultiVisitorNil, RuleError, ValidatorContext, Visitor},
value::ScalarValue,
GraphQLInputObject,
};
struct Being;

View file

@ -1,7 +1,11 @@
use crate::parser::{ParseError, ScalarToken};
use juniper_codegen::GraphQLScalarValueInternal as GraphQLScalarValue;
use std::fmt;
use serde::{de, ser::Serialize};
use std::fmt::{self, Debug, Display};
use crate::{
parser::{ParseError, ScalarToken},
GraphQLScalarValue,
};
/// The result of converting a string into a scalar value
pub type ParseScalarResult<'a, S = DefaultScalarValue> = Result<S, ParseError<'a>>;
@ -164,7 +168,15 @@ pub trait ParseScalarValue<S = DefaultScalarValue> {
/// # fn main() {}
/// ```
pub trait ScalarValue:
Debug + Display + PartialEq + Clone + Serialize + From<String> + From<bool> + From<i32> + From<f64>
fmt::Debug
+ fmt::Display
+ PartialEq
+ Clone
+ Serialize
+ From<String>
+ From<bool>
+ From<i32>
+ From<f64>
{
/// Serde visitor used to deserialize this scalar value
type Visitor: for<'de> de::Visitor<'de, Value = Self> + Default;

View file

@ -1,16 +1,13 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{ext::IdentExt, spanned::Spanned, Data, Fields};
use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn impl_enum(
ast: syn::DeriveInput,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
pub fn impl_enum(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
if !ast.generics.params.is_empty() {
@ -122,7 +119,7 @@ pub fn impl_enum(
error.unsupported_attribute(scalar.span_ident(), UnsupportedAttribute::Scalar);
}
if name.starts_with("__") && !is_internal {
if !attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
@ -145,9 +142,7 @@ pub fn impl_enum(
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
mode: is_internal.into(),
};
let juniper_crate_name = if is_internal { "crate" } else { "juniper" };
Ok(definition.into_enum_tokens(juniper_crate_name))
Ok(definition.into_enum_tokens())
}

View file

@ -7,11 +7,7 @@ use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn impl_input_object(
ast: syn::DeriveInput,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
pub fn impl_input_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let fields = match ast.data {
Data::Struct(data) => match data.fields {
@ -123,7 +119,7 @@ pub fn impl_input_object(
error.duplicate(duplicates.iter());
}
if name.starts_with("__") && !is_internal {
if !attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
@ -145,9 +141,7 @@ pub fn impl_input_object(
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
mode: is_internal.into(),
};
let juniper_crate_name = if is_internal { "crate" } else { "juniper" };
Ok(definition.into_input_object_tokens(juniper_crate_name))
Ok(definition.into_input_object_tokens())
}

View file

@ -6,11 +6,7 @@ use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(
ast: syn::DeriveInput,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let struct_fields = match ast.data {
Data::Struct(data) => match data.fields {
@ -105,7 +101,7 @@ pub fn build_derive_object(
error.duplicate(duplicates.iter());
}
if name.starts_with("__") && !is_internal {
if !attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
@ -132,9 +128,7 @@ pub fn build_derive_object(
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
mode: is_internal.into(),
};
let juniper_crate_name = if is_internal { "crate" } else { "juniper" };
Ok(definition.into_tokens(juniper_crate_name))
Ok(definition.into_tokens())
}

View file

@ -64,16 +64,12 @@ impl TransparentAttributes {
}
}
pub fn impl_scalar_value(
ast: &syn::DeriveInput,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
pub fn impl_scalar_value(ast: &syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ident = &ast.ident;
match ast.data {
Data::Enum(ref enum_data) => impl_scalar_enum(ident, enum_data, is_internal, error),
Data::Struct(ref struct_data) => impl_scalar_struct(ast, struct_data, is_internal, error),
Data::Enum(ref enum_data) => impl_scalar_enum(ident, enum_data, error),
Data::Struct(ref struct_data) => impl_scalar_struct(ast, struct_data, error),
Data::Union(_) => Err(error.custom_error(ast.span(), "may not be applied to unions")),
}
}
@ -81,7 +77,6 @@ pub fn impl_scalar_value(
fn impl_scalar_struct(
ast: &syn::DeriveInput,
data: &syn::DataStruct,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
let field = match data.fields {
@ -100,21 +95,15 @@ fn impl_scalar_struct(
let inner_ty = &field.ty;
let name = attrs.name.unwrap_or_else(|| ident.to_string());
let crate_name = if is_internal {
quote!(crate)
} else {
quote!(juniper)
};
let description = match attrs.description {
Some(val) => quote!( .description( #val ) ),
None => quote!(),
};
let _async = quote!(
impl <__S> #crate_name::GraphQLValueAsync<__S> for #ident
impl <__S> ::juniper::GraphQLValueAsync<__S> for #ident
where
__S: #crate_name::ScalarValue + Send + Sync,
__S: ::juniper::ScalarValue + Send + Sync,
Self: Send + Sync,
Self::Context: Send + Sync,
Self::TypeInfo: Send + Sync,
@ -122,11 +111,11 @@ fn impl_scalar_struct(
fn resolve_async<'a>(
&'a self,
info: &'a Self::TypeInfo,
selection_set: Option<&'a [#crate_name::Selection<__S>]>,
executor: &'a #crate_name::Executor<Self::Context, __S>,
) -> #crate_name::BoxFuture<'a, #crate_name::ExecutionResult<__S>> {
use #crate_name::futures::future;
let v = #crate_name::GraphQLValue::resolve(self, info, selection_set, executor);
selection_set: Option<&'a [::juniper::Selection<__S>]>,
executor: &'a ::juniper::Executor<Self::Context, __S>,
) -> ::juniper::BoxFuture<'a, ::juniper::ExecutionResult<__S>> {
use ::juniper::futures::future;
let v = ::juniper::GraphQLValue::resolve(self, info, selection_set, executor);
Box::pin(future::ready(v))
}
}
@ -135,9 +124,9 @@ fn impl_scalar_struct(
let content = quote!(
#_async
impl<S> #crate_name::GraphQLType<S> for #ident
impl<S> ::juniper::GraphQLType<S> for #ident
where
S: #crate_name::ScalarValue,
S: ::juniper::ScalarValue,
{
fn name(_: &Self::TypeInfo) -> Option<&'static str> {
Some(#name)
@ -145,8 +134,8 @@ fn impl_scalar_struct(
fn meta<'r>(
info: &Self::TypeInfo,
registry: &mut #crate_name::Registry<'r, S>,
) -> #crate_name::meta::MetaType<'r, S>
registry: &mut ::juniper::Registry<'r, S>,
) -> ::juniper::meta::MetaType<'r, S>
where
S: 'r,
{
@ -156,54 +145,54 @@ fn impl_scalar_struct(
}
}
impl<S> #crate_name::GraphQLValue<S> for #ident
impl<S> ::juniper::GraphQLValue<S> for #ident
where
S: #crate_name::ScalarValue,
S: ::juniper::ScalarValue,
{
type Context = ();
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #crate_name::GraphQLType<S>>::name(info)
<Self as ::juniper::GraphQLType<S>>::name(info)
}
fn resolve(
&self,
info: &(),
selection: Option<&[#crate_name::Selection<S>]>,
executor: &#crate_name::Executor<Self::Context, S>,
) -> #crate_name::ExecutionResult<S> {
#crate_name::GraphQLValue::resolve(&self.0, info, selection, executor)
selection: Option<&[::juniper::Selection<S>]>,
executor: &::juniper::Executor<Self::Context, S>,
) -> ::juniper::ExecutionResult<S> {
::juniper::GraphQLValue::resolve(&self.0, info, selection, executor)
}
}
impl<S> #crate_name::ToInputValue<S> for #ident
impl<S> ::juniper::ToInputValue<S> for #ident
where
S: #crate_name::ScalarValue,
S: ::juniper::ScalarValue,
{
fn to_input_value(&self) -> #crate_name::InputValue<S> {
#crate_name::ToInputValue::to_input_value(&self.0)
fn to_input_value(&self) -> ::juniper::InputValue<S> {
::juniper::ToInputValue::to_input_value(&self.0)
}
}
impl<S> #crate_name::FromInputValue<S> for #ident
impl<S> ::juniper::FromInputValue<S> for #ident
where
S: #crate_name::ScalarValue,
S: ::juniper::ScalarValue,
{
fn from_input_value(v: &#crate_name::InputValue<S>) -> Option<#ident> {
let inner: #inner_ty = #crate_name::FromInputValue::from_input_value(v)?;
fn from_input_value(v: &::juniper::InputValue<S>) -> Option<#ident> {
let inner: #inner_ty = ::juniper::FromInputValue::from_input_value(v)?;
Some(#ident(inner))
}
}
impl<S> #crate_name::ParseScalarValue<S> for #ident
impl<S> ::juniper::ParseScalarValue<S> for #ident
where
S: #crate_name::ScalarValue,
S: ::juniper::ScalarValue,
{
fn from_str<'a>(
value: #crate_name::parser::ScalarToken<'a>,
) -> #crate_name::ParseScalarResult<'a, S> {
<#inner_ty as #crate_name::ParseScalarValue<S>>::from_str(value)
value: ::juniper::parser::ScalarToken<'a>,
) -> ::juniper::ParseScalarResult<'a, S> {
<#inner_ty as ::juniper::ParseScalarValue<S>>::from_str(value)
}
}
);
@ -214,7 +203,6 @@ fn impl_scalar_struct(
fn impl_scalar_enum(
ident: &syn::Ident,
data: &syn::DataEnum,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
let froms = data
@ -223,7 +211,7 @@ fn impl_scalar_enum(
.map(|v| derive_from_variant(v, ident, &error))
.collect::<Result<Vec<_>, _>>()?;
let serialize = derive_serialize(data.variants.iter(), ident, is_internal);
let serialize = derive_serialize(data.variants.iter(), ident);
let display = derive_display(data.variants.iter(), ident);
@ -255,7 +243,7 @@ where
}
}
fn derive_serialize<'a, I>(variants: I, ident: &Ident, is_internal: bool) -> TokenStream
fn derive_serialize<'a, I>(variants: I, ident: &Ident) -> TokenStream
where
I: Iterator<Item = &'a Variant>,
{
@ -264,16 +252,10 @@ where
quote!(#ident::#variant(ref v) => v.serialize(serializer),)
});
let serde_path = if is_internal {
quote!(crate::serde)
} else {
quote!(juniper::serde)
};
quote! {
impl #serde_path::Serialize for #ident {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where S: #serde_path::Serializer
impl ::juniper::serde::Serialize for #ident {
fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
where S: ::juniper::serde::Serializer
{
match *self {
#(#arms)*
@ -302,13 +284,13 @@ fn derive_from_variant(
let variant = &variant.ident;
Ok(quote! {
impl std::convert::From<#ty> for #ident {
impl ::std::convert::From<#ty> for #ident {
fn from(t: #ty) -> Self {
#ident::#variant(t)
}
}
impl<'a> std::convert::From<&'a #ident> for std::option::Option<&'a #ty> {
impl<'a> ::std::convert::From<&'a #ident> for std::option::Option<&'a #ty> {
fn from(t: &'a #ident) -> Self {
match *t {
#ident::#variant(ref t) => std::option::Option::Some(t),
@ -317,7 +299,7 @@ fn derive_from_variant(
}
}
impl std::convert::From<#ident> for std::option::Option<#ty> {
impl ::std::convert::From<#ident> for std::option::Option<#ty> {
fn from(t: #ident) -> Self {
match t {
#ident::#variant(t) => std::option::Option::Some(t),

View file

@ -1,4 +1,4 @@
//! Code generation for `#[graphql_union]`/`#[graphql_union_internal]` macros.
//! Code generation for `#[graphql_union]` macro.
use std::{mem, ops::Deref as _};
@ -8,7 +8,7 @@ use syn::{ext::IdentExt as _, parse_quote, spanned::Spanned as _};
use crate::{
result::GraphQLScope,
util::{path_eq_single, span_container::SpanContainer, unparenthesize, Mode},
util::{path_eq_single, span_container::SpanContainer, unparenthesize},
};
use super::{
@ -16,37 +16,20 @@ use super::{
UnionVariantDefinition, UnionVariantMeta,
};
/// [`GraphQLScope`] of errors for `#[graphql_union]`/`#[graphql_union_internal]` macros.
/// [`GraphQLScope`] of errors for `#[graphql_union]` macro.
const ERR: GraphQLScope = GraphQLScope::UnionAttr;
/// Returns the concrete name of the `proc_macro_attribute` for deriving `GraphQLUnion`
/// implementation depending on the provided `mode`.
fn attr_path(mode: Mode) -> &'static str {
match mode {
Mode::Public => "graphql_union",
Mode::Internal => "graphql_union_internal",
}
}
/// Expands `#[graphql_union]`/`#[graphql_union_internal]` macro into generated code.
pub fn expand(attr_args: TokenStream, body: TokenStream, mode: Mode) -> syn::Result<TokenStream> {
let attr_path = attr_path(mode);
/// Expands `#[graphql_union]` macro into generated code.
pub fn expand(attr_args: TokenStream, body: TokenStream) -> syn::Result<TokenStream> {
let mut ast = syn::parse2::<syn::ItemTrait>(body).map_err(|_| {
syn::Error::new(
Span::call_site(),
format!(
"#[{}] attribute is applicable to trait definitions only",
attr_path,
),
"#[graphql_union] attribute is applicable to trait definitions only",
)
})?;
let mut trait_attrs = Vec::with_capacity(ast.attrs.len() + 1);
trait_attrs.push({
let attr_path = syn::Ident::new(attr_path, Span::call_site());
parse_quote! { #[#attr_path(#attr_args)] }
});
trait_attrs.push(parse_quote! { #[graphql_union(#attr_args)] });
trait_attrs.extend_from_slice(&ast.attrs);
// Remove repeated attributes from the definition, to omit duplicate expansion.
@ -54,7 +37,7 @@ pub fn expand(attr_args: TokenStream, body: TokenStream, mode: Mode) -> syn::Res
.attrs
.into_iter()
.filter_map(|attr| {
if path_eq_single(&attr.path, attr_path) {
if path_eq_single(&attr.path, "graphql_union") {
None
} else {
Some(attr)
@ -62,7 +45,7 @@ pub fn expand(attr_args: TokenStream, body: TokenStream, mode: Mode) -> syn::Res
})
.collect();
let meta = UnionMeta::from_attrs(attr_path, &trait_attrs)?;
let meta = UnionMeta::from_attrs("graphql_union", &trait_attrs)?;
let trait_span = ast.span();
let trait_ident = &ast.ident;
@ -72,7 +55,7 @@ pub fn expand(attr_args: TokenStream, body: TokenStream, mode: Mode) -> syn::Res
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| trait_ident.unraw().to_string());
if matches!(mode, Mode::Public) && name.starts_with("__") {
if !meta.is_internal && name.starts_with("__") {
ERR.no_double_underscore(
meta.name
.as_ref()
@ -85,16 +68,14 @@ pub fn expand(attr_args: TokenStream, body: TokenStream, mode: Mode) -> syn::Res
.items
.iter_mut()
.filter_map(|i| match i {
syn::TraitItem::Method(m) => {
parse_variant_from_trait_method(m, trait_ident, &meta, mode)
}
syn::TraitItem::Method(m) => parse_variant_from_trait_method(m, trait_ident, &meta),
_ => None,
})
.collect();
proc_macro_error::abort_if_dirty();
emerge_union_variants_from_meta(&mut variants, meta.external_resolvers, mode);
emerge_union_variants_from_meta(&mut variants, meta.external_resolvers);
if variants.is_empty() {
ERR.emit_custom(trait_span, "expects at least one union variant");
@ -124,7 +105,6 @@ pub fn expand(attr_args: TokenStream, body: TokenStream, mode: Mode) -> syn::Res
generics: ast.generics.clone(),
variants,
span: trait_span,
mode,
};
Ok(quote! {
@ -144,16 +124,14 @@ fn parse_variant_from_trait_method(
method: &mut syn::TraitItemMethod,
trait_ident: &syn::Ident,
trait_meta: &UnionMeta,
mode: Mode,
) -> Option<UnionVariantDefinition> {
let attr_path = attr_path(mode);
let method_attrs = method.attrs.clone();
// Remove repeated attributes from the method, to omit incorrect expansion.
method.attrs = mem::take(&mut method.attrs)
.into_iter()
.filter_map(|attr| {
if path_eq_single(&attr.path, attr_path) {
if path_eq_single(&attr.path, "graphql_union") {
None
} else {
Some(attr)
@ -161,22 +139,18 @@ fn parse_variant_from_trait_method(
})
.collect();
let meta = UnionVariantMeta::from_attrs(attr_path, &method_attrs)
let meta = UnionVariantMeta::from_attrs("graphql_union", &method_attrs)
.map_err(|e| proc_macro_error::emit_error!(e))
.ok()?;
if let Some(rslvr) = meta.external_resolver {
ERR.custom(
rslvr.span_ident(),
format!(
"cannot use #[{}(with = ...)] attribute on a trait method",
attr_path,
),
"cannot use #[graphql_union(with = ...)] attribute on a trait method",
)
.note(format!(
"instead use #[{0}(ignore)] on the method with #[{0}(on ... = ...)] on the trait \
itself",
attr_path,
.note(String::from(
"instead use #[graphql_union(ignore)] on the method with \
#[graphql_union(on ... = ...)] on the trait itself",
))
.emit()
}
@ -224,19 +198,16 @@ fn parse_variant_from_trait_method(
),
)
.note(format!(
"use `#[{}(ignore)]` attribute to ignore this trait method for union variants \
resolution",
attr_path,
.note(String::from(
"use `#[graphql_union(ignore)]` attribute to ignore this trait method for union \
variants resolution",
))
.emit();
}
if method_context_ty.is_some() {
let crate_path = mode.crate_path();
parse_quote! {
#trait_ident::#method_ident(self, #crate_path::FromContext::from(context))
#trait_ident::#method_ident(self, ::juniper::FromContext::from(context))
}
} else {
parse_quote! {

View file

@ -1,4 +1,4 @@
//! Code generation for `#[derive(GraphQLUnion)]`/`#[derive(GraphQLUnionInternal)]` macros.
//! Code generation for `#[derive(GraphQLUnion)]` macro.
use proc_macro2::TokenStream;
use proc_macro_error::ResultExt as _;
@ -7,7 +7,7 @@ use syn::{ext::IdentExt as _, parse_quote, spanned::Spanned as _, Data, Fields};
use crate::{
result::GraphQLScope,
util::{span_container::SpanContainer, unparenthesize, Mode},
util::{span_container::SpanContainer, unparenthesize},
};
use super::{
@ -15,25 +15,23 @@ use super::{
UnionVariantDefinition, UnionVariantMeta,
};
/// [`GraphQLScope`] of errors for `#[derive(GraphQLUnion)]`/`#[derive(GraphQLUnionInternal)]`
/// macros.
/// [`GraphQLScope`] of errors for `#[derive(GraphQLUnion)]` macro.
const ERR: GraphQLScope = GraphQLScope::UnionDerive;
/// Expands `#[derive(GraphQLUnion)]`/`#[derive(GraphQLUnionInternal)]` macro into generated code.
pub fn expand(input: TokenStream, mode: Mode) -> syn::Result<TokenStream> {
/// Expands `#[derive(GraphQLUnion)]` macro into generated code.
pub fn expand(input: TokenStream) -> syn::Result<TokenStream> {
let ast = syn::parse2::<syn::DeriveInput>(input).unwrap_or_abort();
match &ast.data {
Data::Enum(_) => expand_enum(ast, mode),
Data::Struct(_) => expand_struct(ast, mode),
Data::Enum(_) => expand_enum(ast),
Data::Struct(_) => expand_struct(ast),
_ => Err(ERR.custom_error(ast.span(), "can only be derived for enums and structs")),
}
.map(ToTokens::into_token_stream)
}
/// Expands into generated code a `#[derive(GraphQLUnion)]`/`#[derive(GraphQLUnionInternal)]` macro
/// placed on a Rust enum.
fn expand_enum(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefinition> {
/// Expands into generated code a `#[derive(GraphQLUnion)]` macro placed on a Rust enum.
fn expand_enum(ast: syn::DeriveInput) -> syn::Result<UnionDefinition> {
let meta = UnionMeta::from_attrs("graphql", &ast.attrs)?;
let enum_span = ast.span();
@ -44,7 +42,7 @@ fn expand_enum(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefinition
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| enum_ident.unraw().to_string());
if matches!(mode, Mode::Public) && name.starts_with("__") {
if !meta.is_internal && name.starts_with("__") {
ERR.no_double_underscore(
meta.name
.as_ref()
@ -58,12 +56,12 @@ fn expand_enum(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefinition
_ => unreachable!(),
}
.into_iter()
.filter_map(|var| parse_variant_from_enum_variant(var, &enum_ident, &meta, mode))
.filter_map(|var| parse_variant_from_enum_variant(var, &enum_ident, &meta))
.collect();
proc_macro_error::abort_if_dirty();
emerge_union_variants_from_meta(&mut variants, meta.external_resolvers, mode);
emerge_union_variants_from_meta(&mut variants, meta.external_resolvers);
if variants.is_empty() {
ERR.emit_custom(enum_span, "expects at least one union variant");
@ -88,7 +86,6 @@ fn expand_enum(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefinition
generics: ast.generics,
variants,
span: enum_span,
mode,
})
}
@ -102,7 +99,6 @@ fn parse_variant_from_enum_variant(
var: syn::Variant,
enum_ident: &syn::Ident,
enum_meta: &UnionMeta,
mode: Mode,
) -> Option<UnionVariantDefinition> {
let meta = UnionVariantMeta::from_attrs("graphql", &var.attrs)
.map_err(|e| proc_macro_error::emit_error!(e))
@ -148,11 +144,10 @@ fn parse_variant_from_enum_variant(
);
}
let crate_path = mode.crate_path();
let resolver_fn = rslvr.into_inner();
parse_quote! {
#resolver_fn(self, #crate_path::FromContext::from(context))
#resolver_fn(self, ::juniper::FromContext::from(context))
}
} else {
parse_quote! {
@ -174,9 +169,8 @@ fn parse_variant_from_enum_variant(
})
}
/// Expands into generated code a `#[derive(GraphQLUnion)]`/`#[derive(GraphQLUnionInternal)]` macro
/// placed on a Rust struct.
fn expand_struct(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefinition> {
/// Expands into generated code a `#[derive(GraphQLUnion)]` macro placed on a Rust struct.
fn expand_struct(ast: syn::DeriveInput) -> syn::Result<UnionDefinition> {
let meta = UnionMeta::from_attrs("graphql", &ast.attrs)?;
let struct_span = ast.span();
@ -187,7 +181,7 @@ fn expand_struct(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefiniti
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| struct_ident.unraw().to_string());
if matches!(mode, Mode::Public) && name.starts_with("__") {
if !meta.is_internal && name.starts_with("__") {
ERR.no_double_underscore(
meta.name
.as_ref()
@ -197,7 +191,7 @@ fn expand_struct(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefiniti
}
let mut variants = vec![];
emerge_union_variants_from_meta(&mut variants, meta.external_resolvers, mode);
emerge_union_variants_from_meta(&mut variants, meta.external_resolvers);
if variants.is_empty() {
ERR.emit_custom(struct_span, "expects at least one union variant");
}
@ -221,6 +215,5 @@ fn expand_struct(ast: syn::DeriveInput, mode: Mode) -> syn::Result<UnionDefiniti
generics: ast.generics,
variants,
span: struct_span,
mode,
})
}

View file

@ -15,9 +15,7 @@ use syn::{
spanned::Spanned as _,
};
use crate::util::{
filter_attrs, get_doc_comment, span_container::SpanContainer, Mode, OptionExt as _,
};
use crate::util::{filter_attrs, get_doc_comment, span_container::SpanContainer, OptionExt as _};
/// Attempts to merge an [`Option`]ed `$field` of a `$self` struct with the same `$field` of
/// `$another` struct. If both are [`Some`], then throws a duplication error with a [`Span`] related
@ -122,6 +120,10 @@ struct UnionMeta {
///
/// [1]: https://spec.graphql.org/June2018/#sec-Unions
pub external_resolvers: UnionMetaResolvers,
/// Indicator whether the generated code is intended to be used only inside the `juniper`
/// library.
pub is_internal: bool,
}
impl Parse for UnionMeta {
@ -182,6 +184,9 @@ impl Parse for UnionMeta {
.insert(ty, rslvr_spanned)
.none_or_else(|_| dup_attr_err(rslvr_span))?
}
"internal" => {
output.is_internal = true;
}
_ => {
return Err(syn::Error::new(ident.span(), "unknown attribute"));
}
@ -204,6 +209,7 @@ impl UnionMeta {
context: try_merge_opt!(context: self, another),
scalar: try_merge_opt!(scalar: self, another),
external_resolvers: try_merge_hashmap!(external_resolvers: self, another => span_joined),
is_internal: self.is_internal || another.is_internal,
})
}
@ -389,17 +395,10 @@ struct UnionDefinition {
///
/// [1]: https://spec.graphql.org/June2018/#sec-Unions
pub span: Span,
/// [`Mode`] to generate code in for this [GraphQL union][1].
///
/// [1]: https://spec.graphql.org/June2018/#sec-Unions
pub mode: Mode,
}
impl ToTokens for UnionDefinition {
fn to_tokens(&self, into: &mut TokenStream) {
let crate_path = self.mode.crate_path();
let name = &self.name;
let ty = &self.ty;
@ -423,7 +422,7 @@ impl ToTokens for UnionDefinition {
let var_types: Vec<_> = self.variants.iter().map(|var| &var.ty).collect();
let all_variants_unique = if var_types.len() > 1 {
Some(quote! { #crate_path::sa::assert_type_ne_all!(#(#var_types),*); })
Some(quote! { ::juniper::sa::assert_type_ne_all!(#(#var_types),*); })
} else {
None
};
@ -433,7 +432,7 @@ impl ToTokens for UnionDefinition {
let var_check = &var.resolver_check;
quote! {
if #var_check {
return <#var_ty as #crate_path::GraphQLType<#scalar>>::name(&())
return <#var_ty as ::juniper::GraphQLType<#scalar>>::name(&())
.unwrap().to_string();
}
}
@ -443,16 +442,16 @@ impl ToTokens for UnionDefinition {
let resolve_into_type = self.variants.iter().zip(match_resolves.iter()).map(|(var, expr)| {
let var_ty = &var.ty;
let get_name = quote! { (<#var_ty as #crate_path::GraphQLType<#scalar>>::name(&())) };
let get_name = quote! { (<#var_ty as ::juniper::GraphQLType<#scalar>>::name(&())) };
quote! {
if type_name == #get_name.unwrap() {
return #crate_path::IntoResolvable::into(
return ::juniper::IntoResolvable::into(
{ #expr },
executor.context()
)
.and_then(|res| match res {
Some((ctx, r)) => executor.replaced_context(ctx).resolve_with_ctx(&(), &r),
None => Ok(#crate_path::Value::null()),
None => Ok(::juniper::Value::null()),
});
}
}
@ -465,21 +464,21 @@ impl ToTokens for UnionDefinition {
let var_ty = &var.ty;
let get_name = quote! {
(<#var_ty as #crate_path::GraphQLType<#scalar>>::name(&()))
(<#var_ty as ::juniper::GraphQLType<#scalar>>::name(&()))
};
quote! {
if type_name == #get_name.unwrap() {
let res = #crate_path::IntoResolvable::into(
let res = ::juniper::IntoResolvable::into(
{ #expr },
executor.context()
);
return #crate_path::futures::future::FutureExt::boxed(async move {
return ::juniper::futures::future::FutureExt::boxed(async move {
match res? {
Some((ctx, r)) => {
let subexec = executor.replaced_context(ctx);
subexec.resolve_with_ctx_async(&(), &r).await
},
None => Ok(#crate_path::Value::null()),
None => Ok(::juniper::Value::null()),
}
});
}
@ -498,7 +497,7 @@ impl ToTokens for UnionDefinition {
.where_clause
.get_or_insert_with(|| parse_quote! { where })
.predicates
.push(parse_quote! { #scalar: #crate_path::ScalarValue });
.push(parse_quote! { #scalar: ::juniper::ScalarValue });
}
let (ext_impl_generics, _, where_clause) = ext_generics.split_for_impl();
@ -521,7 +520,7 @@ impl ToTokens for UnionDefinition {
let type_impl = quote! {
#[automatically_derived]
impl#ext_impl_generics #crate_path::GraphQLType<#scalar> for #ty_full
impl#ext_impl_generics ::juniper::GraphQLType<#scalar> for #ty_full
#where_clause
{
fn name(_ : &Self::TypeInfo) -> Option<&'static str> {
@ -530,8 +529,8 @@ impl ToTokens for UnionDefinition {
fn meta<'r>(
info: &Self::TypeInfo,
registry: &mut #crate_path::Registry<'r, #scalar>
) -> #crate_path::meta::MetaType<'r, #scalar>
registry: &mut ::juniper::Registry<'r, #scalar>
) -> ::juniper::meta::MetaType<'r, #scalar>
where #scalar: 'r,
{
let types = &[
@ -546,14 +545,14 @@ impl ToTokens for UnionDefinition {
let value_impl = quote! {
#[automatically_derived]
impl#ext_impl_generics #crate_path::GraphQLValue<#scalar> for #ty_full
impl#ext_impl_generics ::juniper::GraphQLValue<#scalar> for #ty_full
#where_clause
{
type Context = #context;
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #crate_path::GraphQLType<#scalar>>::name(info)
<Self as ::juniper::GraphQLType<#scalar>>::name(info)
}
fn concrete_type_name(
@ -573,9 +572,9 @@ impl ToTokens for UnionDefinition {
&self,
_: &Self::TypeInfo,
type_name: &str,
_: Option<&[#crate_path::Selection<#scalar>]>,
executor: &#crate_path::Executor<Self::Context, #scalar>,
) -> #crate_path::ExecutionResult<#scalar> {
_: Option<&[::juniper::Selection<#scalar>]>,
executor: &::juniper::Executor<Self::Context, #scalar>,
) -> ::juniper::ExecutionResult<#scalar> {
let context = executor.context();
#( #resolve_into_type )*
panic!(
@ -588,16 +587,16 @@ impl ToTokens for UnionDefinition {
let value_async_impl = quote! {
#[automatically_derived]
impl#ext_impl_generics #crate_path::GraphQLValueAsync<#scalar> for #ty_full
impl#ext_impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty_full
#where_async
{
fn resolve_into_type_async<'b>(
&'b self,
_: &'b Self::TypeInfo,
type_name: &str,
_: Option<&'b [#crate_path::Selection<'b, #scalar>]>,
executor: &'b #crate_path::Executor<'b, 'b, Self::Context, #scalar>
) -> #crate_path::BoxFuture<'b, #crate_path::ExecutionResult<#scalar>> {
_: Option<&'b [::juniper::Selection<'b, #scalar>]>,
executor: &'b ::juniper::Executor<'b, 'b, Self::Context, #scalar>
) -> ::juniper::BoxFuture<'b, ::juniper::ExecutionResult<#scalar>> {
let context = executor.context();
#( #resolve_into_type_async )*
panic!(
@ -610,24 +609,24 @@ impl ToTokens for UnionDefinition {
let output_type_impl = quote! {
#[automatically_derived]
impl#ext_impl_generics #crate_path::marker::IsOutputType<#scalar> for #ty_full
impl#ext_impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty_full
#where_clause
{
fn mark() {
#( <#var_types as #crate_path::marker::GraphQLObjectType<#scalar>>::mark(); )*
#( <#var_types as ::juniper::marker::GraphQLObjectType<#scalar>>::mark(); )*
}
}
};
let union_impl = quote! {
#[automatically_derived]
impl#ext_impl_generics #crate_path::marker::GraphQLUnion<#scalar> for #ty_full
impl#ext_impl_generics ::juniper::marker::GraphQLUnion<#scalar> for #ty_full
#where_clause
{
fn mark() {
#all_variants_unique
#( <#var_types as #crate_path::marker::GraphQLObjectType<#scalar>>::mark(); )*
#( <#var_types as ::juniper::marker::GraphQLObjectType<#scalar>>::mark(); )*
}
}
};
@ -651,20 +650,17 @@ impl ToTokens for UnionDefinition {
fn emerge_union_variants_from_meta(
variants: &mut Vec<UnionVariantDefinition>,
external_resolvers: UnionMetaResolvers,
mode: Mode,
) {
if external_resolvers.is_empty() {
return;
}
let crate_path = mode.crate_path();
for (ty, rslvr) in external_resolvers {
let span = rslvr.span_joined();
let resolver_fn = rslvr.into_inner();
let resolver_code = parse_quote! {
#resolver_fn(self, #crate_path::FromContext::from(context))
#resolver_fn(self, ::juniper::FromContext::from(context))
};
// Doing this may be quite an expensive, because resolving may contain some heavy
// computation, so we're preforming it twice. Unfortunately, we have no other options here,

View file

@ -9,43 +9,30 @@ use quote::quote;
use syn::{ext::IdentExt, spanned::Spanned};
/// Generate code for the juniper::graphql_object macro.
pub fn build_object(
args: TokenStream,
body: TokenStream,
is_internal: bool,
error: GraphQLScope,
) -> TokenStream {
let definition = match create(args, body, is_internal, error) {
pub fn build_object(args: TokenStream, body: TokenStream, error: GraphQLScope) -> TokenStream {
let definition = match create(args, body, error) {
Ok(definition) => definition,
Err(err) => return err.to_compile_error(),
};
let juniper_crate_name = if is_internal { "crate" } else { "juniper" };
definition.into_tokens(juniper_crate_name).into()
definition.into_tokens().into()
}
/// Generate code for the juniper::graphql_subscription macro.
pub fn build_subscription(
args: TokenStream,
body: TokenStream,
is_internal: bool,
error: GraphQLScope,
) -> TokenStream {
let definition = match create(args, body, is_internal, error) {
let definition = match create(args, body, error) {
Ok(definition) => definition,
Err(err) => return err.to_compile_error(),
};
let juniper_crate_name = if is_internal { "crate" } else { "juniper" };
definition
.into_subscription_tokens(juniper_crate_name)
.into()
definition.into_subscription_tokens().into()
}
fn create(
args: TokenStream,
body: TokenStream,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<util::GraphQLTypeDefiniton> {
let body_span = body.span();
@ -190,7 +177,7 @@ fn create(
None => {}
}
if name.starts_with("__") && !is_internal {
if !_impl.attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = _impl.attrs.name {
name.span_ident()
} else {
@ -228,7 +215,6 @@ fn create(
include_type_generics: false,
generic_scalar: false,
no_async: _impl.attrs.no_async.is_some(),
mode: is_internal.into(),
};
Ok(definition)

View file

@ -176,7 +176,6 @@ impl syn::parse::Parse for ScalarCodegenInput {
pub fn build_scalar(
attributes: TokenStream,
body: TokenStream,
is_internal: bool,
error: GraphQLScope,
) -> syn::Result<TokenStream> {
let body_span = body.span();
@ -220,10 +219,6 @@ pub fn build_scalar(
.name
.map(SpanContainer::into_inner)
.unwrap_or_else(|| impl_for_type.ident.to_string());
let crate_name = match is_internal {
true => quote!(crate),
_ => quote!(juniper),
};
let description = match attrs.description {
Some(val) => quote!(.description(#val)),
None => quote!(),
@ -245,14 +240,14 @@ pub fn build_scalar(
_ => quote!(),
};
let generic_type_bound = match input.custom_data_type_is_struct {
true => quote!(where #generic_type: #crate_name::ScalarValue,),
true => quote!(where #generic_type: ::juniper::ScalarValue,),
_ => quote!(),
};
let _async = quote!(
impl#async_generic_type_decl #crate_name::GraphQLValueAsync<#async_generic_type> for #impl_for_type
impl#async_generic_type_decl ::juniper::GraphQLValueAsync<#async_generic_type> for #impl_for_type
where
#async_generic_type: #crate_name::ScalarValue + Send + Sync,
#async_generic_type: ::juniper::ScalarValue + Send + Sync,
Self: Send + Sync,
Self::Context: Send + Sync,
Self::TypeInfo: Send + Sync,
@ -260,11 +255,11 @@ pub fn build_scalar(
fn resolve_async<'a>(
&'a self,
info: &'a Self::TypeInfo,
selection_set: Option<&'a [#crate_name::Selection<#async_generic_type>]>,
executor: &'a #crate_name::Executor<Self::Context, #async_generic_type>,
) -> #crate_name::BoxFuture<'a, #crate_name::ExecutionResult<#async_generic_type>> {
use #crate_name::futures::future;
let v = #crate_name::GraphQLValue::resolve(self, info, selection_set, executor);
selection_set: Option<&'a [::juniper::Selection<#async_generic_type>]>,
executor: &'a ::juniper::Executor<Self::Context, #async_generic_type>,
) -> ::juniper::BoxFuture<'a, ::juniper::ExecutionResult<#async_generic_type>> {
use ::juniper::futures::future;
let v = ::juniper::GraphQLValue::resolve(self, info, selection_set, executor);
Box::pin(future::ready(v))
}
}
@ -273,13 +268,13 @@ pub fn build_scalar(
let content = quote!(
#_async
impl#generic_type_decl #crate_name::marker::IsInputType<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::marker::IsInputType<#generic_type> for #impl_for_type
#generic_type_bound { }
impl#generic_type_decl #crate_name::marker::IsOutputType<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::marker::IsOutputType<#generic_type> for #impl_for_type
#generic_type_bound { }
impl#generic_type_decl #crate_name::GraphQLType<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::GraphQLType<#generic_type> for #impl_for_type
#generic_type_bound
{
fn name(_: &Self::TypeInfo) -> Option<&'static str> {
@ -288,8 +283,8 @@ pub fn build_scalar(
fn meta<'r>(
info: &Self::TypeInfo,
registry: &mut #crate_name::Registry<'r, #generic_type>,
) -> #crate_name::meta::MetaType<'r, #generic_type>
registry: &mut ::juniper::Registry<'r, #generic_type>,
) -> ::juniper::meta::MetaType<'r, #generic_type>
where
#generic_type: 'r,
{
@ -299,48 +294,48 @@ pub fn build_scalar(
}
}
impl#generic_type_decl #crate_name::GraphQLValue<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::GraphQLValue<#generic_type> for #impl_for_type
#generic_type_bound
{
type Context = ();
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #crate_name::GraphQLType<#generic_type>>::name(info)
<Self as ::juniper::GraphQLType<#generic_type>>::name(info)
}
fn resolve(
&self,
info: &(),
selection: Option<&[#crate_name::Selection<#generic_type>]>,
executor: &#crate_name::Executor<Self::Context, #generic_type>,
) -> #crate_name::ExecutionResult<#generic_type> {
selection: Option<&[::juniper::Selection<#generic_type>]>,
executor: &::juniper::Executor<Self::Context, #generic_type>,
) -> ::juniper::ExecutionResult<#generic_type> {
Ok(#resolve_body)
}
}
impl#generic_type_decl #crate_name::ToInputValue<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::ToInputValue<#generic_type> for #impl_for_type
#generic_type_bound
{
fn to_input_value(&self) -> #crate_name::InputValue<#generic_type> {
fn to_input_value(&self) -> ::juniper::InputValue<#generic_type> {
let v = #resolve_body;
#crate_name::ToInputValue::to_input_value(&v)
::juniper::ToInputValue::to_input_value(&v)
}
}
impl#generic_type_decl #crate_name::FromInputValue<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::FromInputValue<#generic_type> for #impl_for_type
#generic_type_bound
{
fn from_input_value(#from_input_value_arg: &#crate_name::InputValue<#generic_type>) -> #from_input_value_result {
fn from_input_value(#from_input_value_arg: &::juniper::InputValue<#generic_type>) -> #from_input_value_result {
#from_input_value_body
}
}
impl#generic_type_decl #crate_name::ParseScalarValue<#generic_type> for #impl_for_type
impl#generic_type_decl ::juniper::ParseScalarValue<#generic_type> for #impl_for_type
#generic_type_bound
{
fn from_str<'a>(
#from_str_arg: #crate_name::parser::ScalarToken<'a>,
#from_str_arg: ::juniper::parser::ScalarToken<'a>,
) -> #from_str_result {
#from_str_body
}

View file

@ -25,25 +25,11 @@ use proc_macro::TokenStream;
use proc_macro_error::{proc_macro_error, ResultExt as _};
use result::GraphQLScope;
use self::util::Mode;
#[proc_macro_error]
#[proc_macro_derive(GraphQLEnum, attributes(graphql))]
pub fn derive_enum(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_enum::impl_enum(ast, false, GraphQLScope::DeriveEnum);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
}
}
#[proc_macro_error]
#[proc_macro_derive(GraphQLEnumInternal, attributes(graphql))]
#[doc(hidden)]
pub fn derive_enum_internal(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_enum::impl_enum(ast, true, GraphQLScope::DeriveEnum);
let gen = derive_enum::impl_enum(ast, GraphQLScope::DeriveEnum);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
@ -54,19 +40,7 @@ pub fn derive_enum_internal(input: TokenStream) -> TokenStream {
#[proc_macro_derive(GraphQLInputObject, attributes(graphql))]
pub fn derive_input_object(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_input_object::impl_input_object(ast, false, GraphQLScope::DeriveInputObject);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
}
}
#[proc_macro_error]
#[proc_macro_derive(GraphQLInputObjectInternal, attributes(graphql))]
#[doc(hidden)]
pub fn derive_input_object_internal(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_input_object::impl_input_object(ast, true, GraphQLScope::DeriveInputObject);
let gen = derive_input_object::impl_input_object(ast, GraphQLScope::DeriveInputObject);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
@ -77,18 +51,7 @@ pub fn derive_input_object_internal(input: TokenStream) -> TokenStream {
#[proc_macro_derive(GraphQLObject, attributes(graphql))]
pub fn derive_object(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_object::build_derive_object(ast, false, GraphQLScope::DeriveObject);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
}
}
#[proc_macro_error]
#[proc_macro_derive(GraphQLObjectInternal, attributes(graphql))]
pub fn derive_object_internal(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_object::build_derive_object(ast, true, GraphQLScope::DeriveObject);
let gen = derive_object::build_derive_object(ast, GraphQLScope::DeriveObject);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
@ -141,19 +104,7 @@ pub fn derive_object_internal(input: TokenStream) -> TokenStream {
#[proc_macro_derive(GraphQLScalarValue, attributes(graphql))]
pub fn derive_scalar_value(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_scalar_value::impl_scalar_value(&ast, false, GraphQLScope::DeriveScalar);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
}
}
#[proc_macro_error]
#[proc_macro_derive(GraphQLScalarValueInternal)]
#[doc(hidden)]
pub fn derive_scalar_value_internal(input: TokenStream) -> TokenStream {
let ast = syn::parse::<syn::DeriveInput>(input).unwrap();
let gen = derive_scalar_value::impl_scalar_value(&ast, true, GraphQLScope::DeriveScalar);
let gen = derive_scalar_value::impl_scalar_value(&ast, GraphQLScope::DeriveScalar);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
@ -423,22 +374,6 @@ pub fn graphql_object(args: TokenStream, input: TokenStream) -> TokenStream {
TokenStream::from(impl_object::build_object(
args,
input,
false,
GraphQLScope::ImplObject,
))
}
/// A proc macro for defining a GraphQL object.
#[proc_macro_error]
#[proc_macro_attribute]
#[doc(hidden)]
pub fn graphql_object_internal(args: TokenStream, input: TokenStream) -> TokenStream {
let args = proc_macro2::TokenStream::from(args);
let input = proc_macro2::TokenStream::from(input);
TokenStream::from(impl_object::build_object(
args,
input,
true,
GraphQLScope::ImplObject,
))
}
@ -497,21 +432,7 @@ pub fn graphql_object_internal(args: TokenStream, input: TokenStream) -> TokenSt
pub fn graphql_scalar(args: TokenStream, input: TokenStream) -> TokenStream {
let args = proc_macro2::TokenStream::from(args);
let input = proc_macro2::TokenStream::from(input);
let gen = impl_scalar::build_scalar(args, input, false, GraphQLScope::ImplScalar);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
}
}
/// A proc macro for defining a GraphQL scalar.
#[proc_macro_error]
#[proc_macro_attribute]
#[doc(hidden)]
pub fn graphql_scalar_internal(args: TokenStream, input: TokenStream) -> TokenStream {
let args = proc_macro2::TokenStream::from(args);
let input = proc_macro2::TokenStream::from(input);
let gen = impl_scalar::build_scalar(args, input, true, GraphQLScope::ImplScalar);
let gen = impl_scalar::build_scalar(args, input, GraphQLScope::ImplScalar);
match gen {
Ok(gen) => gen.into(),
Err(err) => proc_macro_error::abort!(err),
@ -527,21 +448,6 @@ pub fn graphql_subscription(args: TokenStream, input: TokenStream) -> TokenStrea
TokenStream::from(impl_object::build_subscription(
args,
input,
false,
GraphQLScope::ImplObject,
))
}
#[proc_macro_error]
#[proc_macro_attribute]
#[doc(hidden)]
pub fn graphql_subscription_internal(args: TokenStream, input: TokenStream) -> TokenStream {
let args = proc_macro2::TokenStream::from(args);
let input = proc_macro2::TokenStream::from(input);
TokenStream::from(impl_object::build_subscription(
args,
input,
true,
GraphQLScope::ImplObject,
))
}
@ -847,16 +753,7 @@ pub fn graphql_subscription_internal(args: TokenStream, input: TokenStream) -> T
#[proc_macro_error]
#[proc_macro_derive(GraphQLUnion, attributes(graphql))]
pub fn derive_union(input: TokenStream) -> TokenStream {
self::graphql_union::derive::expand(input.into(), Mode::Public)
.unwrap_or_abort()
.into()
}
#[proc_macro_error]
#[proc_macro_derive(GraphQLUnionInternal, attributes(graphql))]
#[doc(hidden)]
pub fn derive_union_internal(input: TokenStream) -> TokenStream {
self::graphql_union::derive::expand(input.into(), Mode::Internal)
self::graphql_union::derive::expand(input.into())
.unwrap_or_abort()
.into()
}
@ -1146,16 +1043,7 @@ pub fn derive_union_internal(input: TokenStream) -> TokenStream {
#[proc_macro_error]
#[proc_macro_attribute]
pub fn graphql_union(attr: TokenStream, body: TokenStream) -> TokenStream {
self::graphql_union::attr::expand(attr.into(), body.into(), Mode::Public)
.unwrap_or_abort()
.into()
}
#[proc_macro_error]
#[proc_macro_attribute]
#[doc(hidden)]
pub fn graphql_union_internal(attr: TokenStream, body: TokenStream) -> TokenStream {
self::graphql_union::attr::expand(attr.into(), body.into(), Mode::Internal)
self::graphql_union::attr::expand(attr.into(), body.into())
.unwrap_or_abort()
.into()
}

View file

@ -1,7 +1,6 @@
#![allow(clippy::single_match)]
pub mod duplicate;
pub mod mode;
pub mod option_ext;
pub mod parse_impl;
pub mod span_container;
@ -18,7 +17,7 @@ use syn::{
MetaNameValue, NestedMeta, Token,
};
pub use self::{mode::Mode, option_ext::OptionExt};
pub use self::option_ext::OptionExt;
/// Returns the name of a type.
/// If the type does not end in a simple ident, `None` is returned.
@ -305,18 +304,12 @@ pub struct ObjectAttributes {
pub scalar: Option<SpanContainer<syn::Type>>,
pub interfaces: Vec<SpanContainer<syn::Type>>,
pub no_async: Option<SpanContainer<()>>,
pub is_internal: bool,
}
impl syn::parse::Parse for ObjectAttributes {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let mut output = Self {
name: None,
description: None,
context: None,
scalar: None,
interfaces: Vec::new(),
no_async: None,
};
let mut output = Self::default();
while !input.is_empty() {
let ident: syn::Ident = input.parse()?;
@ -374,6 +367,9 @@ impl syn::parse::Parse for ObjectAttributes {
"noasync" => {
output.no_async = Some(SpanContainer::new(ident.span(), None, ()));
}
"internal" => {
output.is_internal = true;
}
_ => {
return Err(syn::Error::new(ident.span(), "unknown attribute"));
}
@ -563,14 +559,7 @@ impl parse::Parse for FieldAttributes {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let items = Punctuated::<FieldAttribute, Token![,]>::parse_terminated(&input)?;
let mut output = Self {
name: None,
description: None,
deprecation: None,
skip: None,
arguments: Default::default(),
default: None,
};
let mut output = Self::default();
for item in items {
match item {
@ -695,7 +684,6 @@ pub struct GraphQLTypeDefiniton {
pub generic_scalar: bool,
// FIXME: make this redundant.
pub no_async: bool,
pub mode: Mode,
}
impl GraphQLTypeDefiniton {
@ -704,9 +692,7 @@ impl GraphQLTypeDefiniton {
self.fields.iter().any(|field| field.is_async)
}
pub fn into_tokens(self, juniper_crate_name: &str) -> TokenStream {
let juniper_crate_name = syn::parse_str::<syn::Path>(juniper_crate_name).unwrap();
pub fn into_tokens(self) -> TokenStream {
let name = &self.name;
let ty = &self._type;
let context = self
@ -780,7 +766,7 @@ impl GraphQLTypeDefiniton {
// See more comments below.
quote!(__S)
} else {
quote!(#juniper_crate_name::DefaultScalarValue)
quote!(::juniper::DefaultScalarValue)
}
});
@ -793,7 +779,7 @@ impl GraphQLTypeDefiniton {
#name => {
panic!("Tried to resolve async field {} on type {:?} with a sync resolver",
#name,
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(_info)
<Self as ::juniper::GraphQLType<#scalar>>::name(_info)
);
},
)
@ -807,14 +793,14 @@ impl GraphQLTypeDefiniton {
quote!(
#name => {
let res #_type = (|| { #code })();
#juniper_crate_name::IntoResolvable::into(
::juniper::IntoResolvable::into(
res,
executor.context()
)
.and_then(|res| {
match res {
Some((ctx, r)) => executor.replaced_context(ctx).resolve_with_ctx(&(), &r),
None => Ok(#juniper_crate_name::Value::null()),
None => Ok(::juniper::Value::null()),
}
})
},
@ -852,7 +838,7 @@ impl GraphQLTypeDefiniton {
// Insert ScalarValue constraint.
where_clause
.predicates
.push(parse_quote!(__S: #juniper_crate_name::ScalarValue));
.push(parse_quote!(__S: ::juniper::ScalarValue));
}
let type_generics_tokens = if self.include_type_generics {
@ -879,7 +865,7 @@ impl GraphQLTypeDefiniton {
let f = async move {
let res #_type = async move { #code }.await;
let inner_res = #juniper_crate_name::IntoResolvable::into(
let inner_res = ::juniper::IntoResolvable::into(
res,
executor.context()
);
@ -890,11 +876,11 @@ impl GraphQLTypeDefiniton {
subexec.resolve_with_ctx_async(&(), &r)
.await
},
Ok(None) => Ok(#juniper_crate_name::Value::null()),
Ok(None) => Ok(::juniper::Value::null()),
Err(e) => Err(e),
}
};
use #juniper_crate_name::futures::future;
use ::juniper::futures::future;
future::FutureExt::boxed(f)
},
)
@ -907,21 +893,21 @@ impl GraphQLTypeDefiniton {
let sub = executor.replaced_context(ctx);
sub.resolve_with_ctx_async(&(), &r).await
},
Ok(None) => Ok(#juniper_crate_name::Value::null()),
Ok(None) => Ok(::juniper::Value::null()),
Err(e) => Err(e),
}
};
use #juniper_crate_name::futures::future;
use ::juniper::futures::future;
future::FutureExt::boxed(f)
)
} else {
quote!(
let v = match res2 {
Ok(Some((ctx, r))) => executor.replaced_context(ctx).resolve_with_ctx(&(), &r),
Ok(None) => Ok(#juniper_crate_name::Value::null()),
Ok(None) => Ok(::juniper::Value::null()),
Err(e) => Err(e),
};
use #juniper_crate_name::futures::future;
use ::juniper::futures::future;
future::FutureExt::boxed(future::ready(v))
)
};
@ -929,7 +915,7 @@ impl GraphQLTypeDefiniton {
quote!(
#name => {
let res #_type = (||{ #code })();
let res2 = #juniper_crate_name::IntoResolvable::into(
let res2 = ::juniper::IntoResolvable::into(
res,
executor.context()
);
@ -949,26 +935,26 @@ impl GraphQLTypeDefiniton {
// FIXME: add where clause for interfaces.
quote!(
impl#impl_generics #juniper_crate_name::GraphQLValueAsync<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty #type_generics_tokens
#where_async
{
fn resolve_field_async<'b>(
&'b self,
info: &'b Self::TypeInfo,
field: &'b str,
args: &'b #juniper_crate_name::Arguments<#scalar>,
executor: &'b #juniper_crate_name::Executor<Self::Context, #scalar>,
) -> #juniper_crate_name::BoxFuture<'b, #juniper_crate_name::ExecutionResult<#scalar>>
args: &'b ::juniper::Arguments<#scalar>,
executor: &'b ::juniper::Executor<Self::Context, #scalar>,
) -> ::juniper::BoxFuture<'b, ::juniper::ExecutionResult<#scalar>>
where #scalar: Send + Sync,
{
use #juniper_crate_name::futures::future;
use #juniper_crate_name::GraphQLType;
use ::juniper::futures::future;
use ::juniper::GraphQLType;
match field {
#( #resolve_matches_async )*
_ => {
panic!("Field {} not found on type {:?}",
field,
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(info)
<Self as ::juniper::GraphQLType<#scalar>>::name(info)
);
}
}
@ -983,27 +969,27 @@ impl GraphQLTypeDefiniton {
// let field_marks = field.args.iter().map(|arg| {
// let arg_ty = &arg._type;
// quote!(<#arg_ty as #juniper_crate_name::marker::IsInputType<#scalar>>::mark();)
// quote!(<#arg_ty as ::juniper::marker::IsInputType<#scalar>>::mark();)
// });
// quote!(
// #( #field_marks)*
// <#field_ty as #juniper_crate_name::marker::IsOutputType<#scalar>>::mark();
// <#field_ty as ::juniper::marker::IsOutputType<#scalar>>::mark();
// )
// });
let output = quote!(
impl#impl_generics #juniper_crate_name::marker::IsOutputType<#scalar> for #ty #type_generics_tokens #where_clause {
impl#impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty #type_generics_tokens #where_clause {
fn mark() {
// FIXME: enable this if interfaces are supported
// #( #marks )*
}
}
impl#impl_generics #juniper_crate_name::marker::GraphQLObjectType<#scalar> for #ty #type_generics_tokens #where_clause
impl#impl_generics ::juniper::marker::GraphQLObjectType<#scalar> for #ty #type_generics_tokens #where_clause
{ }
impl#impl_generics #juniper_crate_name::GraphQLType<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLType<#scalar> for #ty #type_generics_tokens
#where_clause
{
fn name(_: &Self::TypeInfo) -> Option<&'static str> {
@ -1012,8 +998,8 @@ impl GraphQLTypeDefiniton {
fn meta<'r>(
info: &Self::TypeInfo,
registry: &mut #juniper_crate_name::Registry<'r, #scalar>
) -> #juniper_crate_name::meta::MetaType<'r, #scalar>
registry: &mut ::juniper::Registry<'r, #scalar>
) -> ::juniper::meta::MetaType<'r, #scalar>
where #scalar : 'r,
{
let fields = vec![
@ -1026,14 +1012,14 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::GraphQLValue<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty #type_generics_tokens
#where_clause
{
type Context = #context;
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(info)
<Self as ::juniper::GraphQLType<#scalar>>::name(info)
}
#[allow(unused_variables)]
@ -1042,15 +1028,15 @@ impl GraphQLTypeDefiniton {
&self,
_info: &(),
field: &str,
args: &#juniper_crate_name::Arguments<#scalar>,
executor: &#juniper_crate_name::Executor<Self::Context, #scalar>,
) -> #juniper_crate_name::ExecutionResult<#scalar> {
args: &::juniper::Arguments<#scalar>,
executor: &::juniper::Executor<Self::Context, #scalar>,
) -> ::juniper::ExecutionResult<#scalar> {
match field {
#( #resolve_matches )*
_ => {
panic!("Field {} not found on type {:?}",
field,
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(_info)
<Self as ::juniper::GraphQLType<#scalar>>::name(_info)
);
}
}
@ -1068,9 +1054,7 @@ impl GraphQLTypeDefiniton {
output
}
pub fn into_subscription_tokens(self, juniper_crate_name: &str) -> TokenStream {
let juniper_crate_name = syn::parse_str::<syn::Path>(juniper_crate_name).unwrap();
pub fn into_subscription_tokens(self) -> TokenStream {
let name = &self.name;
let ty = &self._type;
let context = self
@ -1089,7 +1073,7 @@ impl GraphQLTypeDefiniton {
// See more comments below.
quote!(__S)
} else {
quote!(#juniper_crate_name::DefaultScalarValue)
quote!(::juniper::DefaultScalarValue)
}
});
@ -1142,7 +1126,7 @@ impl GraphQLTypeDefiniton {
let _type;
if field.is_async {
_type = quote!(<#type_name as #juniper_crate_name::ExtractTypeFromStream<_, #scalar>>::Item);
_type = quote!(<#type_name as ::juniper::ExtractTypeFromStream<_, #scalar>>::Item);
} else {
panic!("Synchronous resolvers are not supported. Specify that this function is async: 'async fn foo()'")
}
@ -1186,7 +1170,7 @@ impl GraphQLTypeDefiniton {
// Insert ScalarValue constraint.
where_clause
.predicates
.push(parse_quote!(__S: #juniper_crate_name::ScalarValue));
.push(parse_quote!(__S: ::juniper::ScalarValue));
}
let type_generics_tokens = if self.include_type_generics {
@ -1196,10 +1180,8 @@ impl GraphQLTypeDefiniton {
};
let (impl_generics, _, where_clause) = generics.split_for_impl();
let resolve_matches_async = self.fields
.iter()
.filter(|field| field.is_async)
.map(|field| {
let resolve_matches_async = self.fields.iter().filter(|field| field.is_async).map(
|field| {
let name = &field.name;
let code = &field.resolver_code;
@ -1212,14 +1194,14 @@ impl GraphQLTypeDefiniton {
};
quote!(
#name => {
#juniper_crate_name::futures::FutureExt::boxed(async move {
::juniper::futures::FutureExt::boxed(async move {
let res #_type = { #code };
let res = #juniper_crate_name::IntoFieldResult::<_, #scalar>::into_result(res)?;
let res = ::juniper::IntoFieldResult::<_, #scalar>::into_result(res)?;
let executor= executor.as_owned_executor();
let f = res.then(move |res| {
let executor = executor.clone();
let res2: #juniper_crate_name::FieldResult<_, #scalar> =
#juniper_crate_name::IntoResolvable::into(res, executor.context());
let res2: ::juniper::FieldResult<_, #scalar> =
::juniper::IntoResolvable::into(res, executor.context());
async move {
let ex = executor.as_executor();
match res2 {
@ -1235,18 +1217,18 @@ impl GraphQLTypeDefiniton {
}
});
Ok(
#juniper_crate_name::Value::Scalar::<
#juniper_crate_name::ValuesStream
::juniper::Value::Scalar::<
::juniper::ValuesStream
>(Box::pin(f))
)
})
}
)
});
},
);
let graphql_implementation = quote!(
impl#impl_generics #juniper_crate_name::GraphQLType<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLType<#scalar> for #ty #type_generics_tokens
#where_clause
{
fn name(_: &Self::TypeInfo) -> Option<&'static str> {
@ -1255,8 +1237,8 @@ impl GraphQLTypeDefiniton {
fn meta<'r>(
info: &Self::TypeInfo,
registry: &mut #juniper_crate_name::Registry<'r, #scalar>
) -> #juniper_crate_name::meta::MetaType<'r, #scalar>
registry: &mut ::juniper::Registry<'r, #scalar>
) -> ::juniper::meta::MetaType<'r, #scalar>
where #scalar : 'r,
{
let fields = vec![
@ -1269,23 +1251,23 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::GraphQLValue<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty #type_generics_tokens
#where_clause
{
type Context = #context;
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(info)
<Self as ::juniper::GraphQLType<#scalar>>::name(info)
}
fn resolve_field(
&self,
_: &(),
_: &str,
_: &#juniper_crate_name::Arguments<#scalar>,
_: &#juniper_crate_name::Executor<Self::Context, #scalar>,
) -> #juniper_crate_name::ExecutionResult<#scalar> {
_: &::juniper::Arguments<#scalar>,
_: &::juniper::Executor<Self::Context, #scalar>,
) -> ::juniper::ExecutionResult<#scalar> {
panic!("Called `resolve_field` on subscription object");
}
@ -1297,7 +1279,7 @@ impl GraphQLTypeDefiniton {
);
let subscription_implementation = quote!(
impl#impl_generics #juniper_crate_name::GraphQLSubscriptionValue<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLSubscriptionValue<#scalar> for #ty #type_generics_tokens
#where_clause
{
#[allow(unused_variables)]
@ -1307,13 +1289,13 @@ impl GraphQLTypeDefiniton {
&'s self,
info: &'i Self::TypeInfo,
field_name: &'fi str,
args: #juniper_crate_name::Arguments<'args, #scalar>,
executor: &'ref_e #juniper_crate_name::Executor<'ref_e, 'e, Self::Context, #scalar>,
args: ::juniper::Arguments<'args, #scalar>,
executor: &'ref_e ::juniper::Executor<'ref_e, 'e, Self::Context, #scalar>,
) -> std::pin::Pin<Box<
dyn #juniper_crate_name::futures::future::Future<
dyn ::juniper::futures::future::Future<
Output = Result<
#juniper_crate_name::Value<#juniper_crate_name::ValuesStream<'res, #scalar>>,
#juniper_crate_name::FieldError<#scalar>
::juniper::Value<::juniper::ValuesStream<'res, #scalar>>,
::juniper::FieldError<#scalar>
>
> + Send + 'f
>>
@ -1326,8 +1308,8 @@ impl GraphQLTypeDefiniton {
'ref_e: 'f,
'res: 'f,
{
use #juniper_crate_name::Value;
use #juniper_crate_name::futures::stream::StreamExt as _;
use ::juniper::Value;
use ::juniper::futures::stream::StreamExt as _;
match field_name {
#( #resolve_matches_async )*
@ -1345,9 +1327,7 @@ impl GraphQLTypeDefiniton {
)
}
pub fn into_enum_tokens(self, juniper_crate_name: &str) -> TokenStream {
let juniper_crate_name = syn::parse_str::<syn::Path>(juniper_crate_name).unwrap();
pub fn into_enum_tokens(self) -> TokenStream {
let name = &self.name;
let ty = &self._type;
let context = self
@ -1366,7 +1346,7 @@ impl GraphQLTypeDefiniton {
// See more comments below.
quote!(__S)
} else {
quote!(#juniper_crate_name::DefaultScalarValue)
quote!(::juniper::DefaultScalarValue)
}
});
@ -1388,13 +1368,13 @@ impl GraphQLTypeDefiniton {
.deprecation
.as_ref()
.map(|deprecation| match deprecation.reason.as_ref() {
Some(reason) => quote!( #juniper_crate_name::meta::DeprecationStatus::Deprecated(Some(#reason.to_string())) ),
None => quote!( #juniper_crate_name::meta::DeprecationStatus::Deprecated(None) ),
Some(reason) => quote!( ::juniper::meta::DeprecationStatus::Deprecated(Some(#reason.to_string())) ),
None => quote!( ::juniper::meta::DeprecationStatus::Deprecated(None) ),
})
.unwrap_or_else(|| quote!(#juniper_crate_name::meta::DeprecationStatus::Current));
.unwrap_or_else(|| quote!(::juniper::meta::DeprecationStatus::Current));
quote!(
#juniper_crate_name::meta::EnumValue {
::juniper::meta::EnumValue {
name: #variant_name.to_string(),
description: #descr,
deprecation_status: #depr,
@ -1407,7 +1387,7 @@ impl GraphQLTypeDefiniton {
let resolver_code = &variant.resolver_code;
quote!(
&#resolver_code => #juniper_crate_name::Value::scalar(String::from(#variant_name)),
&#resolver_code => ::juniper::Value::scalar(String::from(#variant_name)),
)
});
@ -1426,7 +1406,7 @@ impl GraphQLTypeDefiniton {
quote!(
&#resolver_code =>
#juniper_crate_name::InputValue::scalar(#variant_name.to_string()),
::juniper::InputValue::scalar(#variant_name.to_string()),
)
});
@ -1442,7 +1422,7 @@ impl GraphQLTypeDefiniton {
// Insert ScalarValue constraint.
where_clause
.predicates
.push(parse_quote!(__S: #juniper_crate_name::ScalarValue));
.push(parse_quote!(__S: ::juniper::ScalarValue));
}
let (impl_generics, _, where_clause) = generics.split_for_impl();
@ -1454,31 +1434,30 @@ impl GraphQLTypeDefiniton {
where_async.predicates.push(parse_quote!(Self: Send + Sync));
let _async = quote!(
impl#impl_generics #juniper_crate_name::GraphQLValueAsync<#scalar> for #ty
impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty
#where_async
{
fn resolve_async<'a>(
&'a self,
info: &'a Self::TypeInfo,
selection_set: Option<&'a [#juniper_crate_name::Selection<#scalar>]>,
executor: &'a #juniper_crate_name::Executor<Self::Context, #scalar>,
) -> #juniper_crate_name::BoxFuture<'a, #juniper_crate_name::ExecutionResult<#scalar>> {
use #juniper_crate_name::GraphQLValue as _;
use #juniper_crate_name::futures::future;
let v = self.resolve(info, selection_set, executor);
selection_set: Option<&'a [::juniper::Selection<#scalar>]>,
executor: &'a ::juniper::Executor<Self::Context, #scalar>,
) -> ::juniper::BoxFuture<'a, ::juniper::ExecutionResult<#scalar>> {
use ::juniper::futures::future;
let v = ::juniper::GraphQLValue::resolve(self, info, selection_set, executor);
future::FutureExt::boxed(future::ready(v))
}
}
);
let mut body = quote!(
impl#impl_generics #juniper_crate_name::marker::IsInputType<#scalar> for #ty
impl#impl_generics ::juniper::marker::IsInputType<#scalar> for #ty
#where_clause { }
impl#impl_generics #juniper_crate_name::marker::IsOutputType<#scalar> for #ty
impl#impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty
#where_clause { }
impl#impl_generics #juniper_crate_name::GraphQLType<#scalar> for #ty
impl#impl_generics ::juniper::GraphQLType<#scalar> for #ty
#where_clause
{
fn name(_: &()) -> Option<&'static str> {
@ -1487,8 +1466,8 @@ impl GraphQLTypeDefiniton {
fn meta<'r>(
_: &(),
registry: &mut #juniper_crate_name::Registry<'r, #scalar>
) -> #juniper_crate_name::meta::MetaType<'r, #scalar>
registry: &mut ::juniper::Registry<'r, #scalar>
) -> ::juniper::meta::MetaType<'r, #scalar>
where #scalar: 'r,
{
registry.build_enum_type::<#ty>(&(), &[
@ -1499,22 +1478,22 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::GraphQLValue<#scalar> for #ty
impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty
#where_clause
{
type Context = #context;
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(info)
<Self as ::juniper::GraphQLType<#scalar>>::name(info)
}
fn resolve(
&self,
_: &(),
_: Option<&[#juniper_crate_name::Selection<#scalar>]>,
_: &#juniper_crate_name::Executor<Self::Context, #scalar>
) -> #juniper_crate_name::ExecutionResult<#scalar> {
_: Option<&[::juniper::Selection<#scalar>]>,
_: &::juniper::Executor<Self::Context, #scalar>
) -> ::juniper::ExecutionResult<#scalar> {
let v = match self {
#( #resolves )*
};
@ -1522,10 +1501,10 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::FromInputValue<#scalar> for #ty
impl#impl_generics ::juniper::FromInputValue<#scalar> for #ty
#where_clause
{
fn from_input_value(v: &#juniper_crate_name::InputValue<#scalar>) -> Option<#ty>
fn from_input_value(v: &::juniper::InputValue<#scalar>) -> Option<#ty>
{
match v.as_enum_value().or_else(|| {
v.as_string_value()
@ -1536,10 +1515,10 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::ToInputValue<#scalar> for #ty
impl#impl_generics ::juniper::ToInputValue<#scalar> for #ty
#where_clause
{
fn to_input_value(&self) -> #juniper_crate_name::InputValue<#scalar> {
fn to_input_value(&self) -> ::juniper::InputValue<#scalar> {
match self {
#( #to_inputs )*
}
@ -1554,9 +1533,7 @@ impl GraphQLTypeDefiniton {
body
}
pub fn into_input_object_tokens(self, juniper_crate_name: &str) -> TokenStream {
let juniper_crate_name = syn::parse_str::<syn::Path>(juniper_crate_name).unwrap();
pub fn into_input_object_tokens(self) -> TokenStream {
let name = &self.name;
let ty = &self._type;
let context = self
@ -1575,7 +1552,7 @@ impl GraphQLTypeDefiniton {
// See more comments below.
quote!(__S)
} else {
quote!(#juniper_crate_name::DefaultScalarValue)
quote!(::juniper::DefaultScalarValue)
}
});
@ -1634,7 +1611,7 @@ impl GraphQLTypeDefiniton {
let from_input_default = match field.default {
Some(ref def) => {
quote! {
Some(&&#juniper_crate_name::InputValue::Null) | None if true => #def,
Some(&&::juniper::InputValue::Null) | None if true => #def,
}
}
None => quote! {},
@ -1645,9 +1622,9 @@ impl GraphQLTypeDefiniton {
// TODO: investigate the unwraps here, they seem dangerous!
match obj.get(#field_name) {
#from_input_default
Some(ref v) => #juniper_crate_name::FromInputValue::from_input_value(v).unwrap(),
Some(ref v) => ::juniper::FromInputValue::from_input_value(v).unwrap(),
None => {
#juniper_crate_name::FromInputValue::from_input_value(&#juniper_crate_name::InputValue::<#scalar>::null())
::juniper::FromInputValue::from_input_value(&::juniper::InputValue::<#scalar>::null())
.unwrap()
},
}
@ -1690,7 +1667,7 @@ impl GraphQLTypeDefiniton {
// Insert ScalarValue constraint.
where_clause
.predicates
.push(parse_quote!(__S: #juniper_crate_name::ScalarValue));
.push(parse_quote!(__S: ::juniper::ScalarValue));
}
let type_generics_tokens = if self.include_type_generics {
@ -1709,7 +1686,7 @@ impl GraphQLTypeDefiniton {
where_async.predicates.push(parse_quote!(Self: Send + Sync));
let async_type = quote!(
impl#impl_generics #juniper_crate_name::GraphQLValueAsync<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty #type_generics_tokens
#where_async
{}
);
@ -1717,11 +1694,11 @@ impl GraphQLTypeDefiniton {
// FIXME: enable this if interfaces are supported
// let marks = self.fields.iter().map(|field| {
// let _ty = &field._type;
// quote!(<#_ty as #juniper_crate_name::marker::IsInputType<#scalar>>::mark();)
// quote!(<#_ty as ::juniper::marker::IsInputType<#scalar>>::mark();)
// });
let mut body = quote!(
impl#impl_generics #juniper_crate_name::marker::IsInputType<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::marker::IsInputType<#scalar> for #ty #type_generics_tokens
#where_clause {
fn mark() {
// FIXME: enable this if interfaces are supported
@ -1729,7 +1706,7 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::GraphQLType<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLType<#scalar> for #ty #type_generics_tokens
#where_clause
{
fn name(_: &()) -> Option<&'static str> {
@ -1738,8 +1715,8 @@ impl GraphQLTypeDefiniton {
fn meta<'r>(
_: &(),
registry: &mut #juniper_crate_name::Registry<'r, #scalar>
) -> #juniper_crate_name::meta::MetaType<'r, #scalar>
registry: &mut ::juniper::Registry<'r, #scalar>
) -> ::juniper::meta::MetaType<'r, #scalar>
where #scalar: 'r
{
let fields = &[
@ -1751,21 +1728,21 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::GraphQLValue<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty #type_generics_tokens
#where_clause
{
type Context = #context;
type TypeInfo = ();
fn type_name<'__i>(&self, info: &'__i Self::TypeInfo) -> Option<&'__i str> {
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(info)
<Self as ::juniper::GraphQLType<#scalar>>::name(info)
}
}
impl#impl_generics #juniper_crate_name::FromInputValue<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::FromInputValue<#scalar> for #ty #type_generics_tokens
#where_clause
{
fn from_input_value(value: &#juniper_crate_name::InputValue<#scalar>) -> Option<Self>
fn from_input_value(value: &::juniper::InputValue<#scalar>) -> Option<Self>
{
if let Some(obj) = value.to_object_value() {
let item = #ty {
@ -1779,11 +1756,11 @@ impl GraphQLTypeDefiniton {
}
}
impl#impl_generics #juniper_crate_name::ToInputValue<#scalar> for #ty #type_generics_tokens
impl#impl_generics ::juniper::ToInputValue<#scalar> for #ty #type_generics_tokens
#where_clause
{
fn to_input_value(&self) -> #juniper_crate_name::InputValue<#scalar> {
#juniper_crate_name::InputValue::object(vec![
fn to_input_value(&self) -> ::juniper::InputValue<#scalar> {
::juniper::InputValue::object(vec![
#( #to_inputs )*
].into_iter().collect())
}

View file

@ -1,32 +0,0 @@
//! Code generation mode.
/// Code generation mode for macros.
#[derive(Clone, Copy, Debug)]
pub enum Mode {
/// Generated code is intended to be used by library users.
Public,
/// Generated code is use only inside the library itself.
Internal,
}
impl Mode {
pub fn crate_path(&self) -> syn::Path {
syn::parse_str::<syn::Path>(match self {
Self::Public => "::juniper",
Self::Internal => "crate",
})
.unwrap_or_else(|e| proc_macro_error::abort!(e))
}
}
// TODO: Remove once all macros are refactored with `Mode`.
impl From<bool> for Mode {
fn from(is_internal: bool) -> Self {
if is_internal {
Mode::Internal
} else {
Mode::Public
}
}
}