use core::fmt;
use std::sync::Arc;
use futures::stream::BoxStream;
use indexmap::IndexMap;
use crate::{
Value, ast,
error::{GraphQLError, PathSegment},
execution::ExecutionContext,
fragments::Fragments,
schema::Schema,
};
pub type Name = Arc<str>;
pub(crate) const SMALL_MAP_LIMIT: usize = 12;
#[inline]
pub(crate) fn names_eq(left: &str, right: &str) -> bool {
let left = left.as_bytes();
let right = right.as_bytes();
if left.len() != right.len() {
return false;
}
if left.len() > 8 {
return left == right;
}
let mut index = 0;
while index < left.len() {
if left[index] != right[index] {
return false;
}
index += 1;
}
true
}
pub(crate) fn map_get<'m, V>(map: &'m IndexMap<Name, V>, name: &str) -> Option<&'m V> {
if map.len() <= SMALL_MAP_LIMIT {
return map
.iter()
.find(|(key, _)| names_eq(key, name))
.map(|(_, value)| value);
}
map.get(name)
}
pub type FieldResult = Result<Value, GraphQLError>;
pub type ResolveFuture<'a> = futures::future::BoxFuture<'a, FieldResult>;
pub type SubscriptionStream = BoxStream<'static, FieldResult>;
#[derive(Clone, Debug, PartialEq)]
pub struct AppliedDirective {
pub name: Name,
pub arguments: IndexMap<Name, Value>,
}
impl AppliedDirective {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
arguments: IndexMap::new(),
}
}
#[must_use]
pub fn argument(mut self, name: impl Into<Name>, value: impl Into<Value>) -> Self {
self.arguments.insert(name.into(), value.into());
self
}
#[must_use]
pub fn get_argument(&self, name: &str) -> Option<&Value> {
map_get(&self.arguments, name)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TypeKind {
Scalar,
Object,
Interface,
Union,
Enum,
InputObject,
}
impl TypeKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Scalar => "SCALAR",
Self::Object => "OBJECT",
Self::Interface => "INTERFACE",
Self::Union => "UNION",
Self::Enum => "ENUM",
Self::InputObject => "INPUT_OBJECT",
}
}
}
impl fmt::Display for TypeKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TypeRef {
Named(Name),
List(Box<TypeRef>),
NonNull(Box<TypeRef>),
}
pub(crate) fn interned_builtin(name: &str) -> Option<Name> {
static NAMES: [std::sync::OnceLock<Name>; 6] = [
std::sync::OnceLock::new(),
std::sync::OnceLock::new(),
std::sync::OnceLock::new(),
std::sync::OnceLock::new(),
std::sync::OnceLock::new(),
std::sync::OnceLock::new(),
];
let index = match name {
"String" => 0,
"Int" => 1,
"Float" => 2,
"Boolean" => 3,
"ID" => 4,
"__Type" => 5,
_ => return None,
};
Some(NAMES[index].get_or_init(|| Name::from(name)).clone())
}
impl TypeRef {
#[must_use]
pub fn named(name: impl Into<Name>) -> Self {
Self::Named(name.into())
}
pub(crate) fn named_str(name: &str) -> Self {
Self::Named(interned_builtin(name).unwrap_or_else(|| Name::from(name)))
}
#[must_use]
pub fn string() -> Self {
Self::Named("String".into())
}
#[must_use]
pub fn int() -> Self {
Self::Named("Int".into())
}
#[must_use]
pub fn float() -> Self {
Self::Named("Float".into())
}
#[must_use]
pub fn boolean() -> Self {
Self::Named("Boolean".into())
}
#[must_use]
pub fn id() -> Self {
Self::Named("ID".into())
}
#[must_use]
pub fn list(self) -> Self {
Self::List(Box::new(self))
}
#[must_use]
pub fn non_null(self) -> Self {
match self {
Self::NonNull(_) => self,
other => Self::NonNull(Box::new(other)),
}
}
#[must_use]
pub fn nullable(self) -> Self {
match self {
Self::NonNull(inner) => *inner,
other => other,
}
}
#[must_use]
pub fn named_type(&self) -> &Name {
match self {
Self::Named(name) => name,
Self::List(inner) | Self::NonNull(inner) => inner.named_type(),
}
}
#[must_use]
pub const fn is_non_null(&self) -> bool {
matches!(self, Self::NonNull(_))
}
#[must_use]
pub const fn is_list(&self) -> bool {
matches!(self, Self::List(_))
}
#[must_use]
pub const fn is_named(&self) -> bool {
matches!(self, Self::Named(_))
}
#[must_use]
pub fn list_item(&self) -> Option<&TypeRef> {
match self {
Self::List(inner) => Some(inner),
Self::NonNull(inner) => inner.list_item(),
Self::Named(_) => None,
}
}
}
impl fmt::Display for TypeRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Named(name) => f.write_str(name),
Self::List(inner) => write!(f, "[{inner}]"),
Self::NonNull(inner) => write!(f, "{inner}!"),
}
}
}
impl From<Name> for TypeRef {
fn from(value: Name) -> Self {
Self::Named(value)
}
}
impl From<&str> for TypeRef {
fn from(value: &str) -> Self {
Self::Named(value.into())
}
}
impl From<String> for TypeRef {
fn from(value: String) -> Self {
Self::Named(value.into())
}
}
pub type ScalarSerializeFn = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;
pub type ScalarParseValueFn = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>;
pub type ScalarParseLiteralFn =
Arc<dyn for<'a> Fn(&ast::Value<'a>) -> Result<Value, String> + Send + Sync>;
#[derive(Clone)]
pub struct ScalarType {
pub name: Name,
pub description: Option<Arc<str>>,
pub specified_by_url: Option<Arc<str>>,
pub directives: Vec<AppliedDirective>,
pub(crate) serialize: Option<ScalarSerializeFn>,
pub(crate) parse_value: Option<ScalarParseValueFn>,
pub(crate) parse_literal: Option<ScalarParseLiteralFn>,
pub(crate) builtin: bool,
}
impl fmt::Debug for ScalarType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScalarType")
.field("name", &self.name)
.field("description", &self.description)
.field("specified_by_url", &self.specified_by_url)
.field("directives", &self.directives)
.finish_non_exhaustive()
}
}
impl ScalarType {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
specified_by_url: None,
directives: Vec::new(),
serialize: None,
parse_value: None,
parse_literal: None,
builtin: false,
}
}
fn builtin(mut self) -> Self {
self.builtin = true;
self
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn specified_by_url(mut self, url: impl Into<Arc<str>>) -> Self {
self.specified_by_url = Some(url.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn serialize(
mut self,
function: impl Fn(&Value) -> Result<Value, String> + Send + Sync + 'static,
) -> Self {
self.serialize = Some(Arc::new(function));
self.builtin = false;
self
}
#[must_use]
pub fn parse_value(
mut self,
function: impl Fn(&Value) -> Result<Value, String> + Send + Sync + 'static,
) -> Self {
self.parse_value = Some(Arc::new(function));
self
}
#[must_use]
pub fn parse_literal(
mut self,
function: impl for<'a> Fn(&ast::Value<'a>) -> Result<Value, String> + Send + Sync + 'static,
) -> Self {
self.parse_literal = Some(Arc::new(function));
self
}
#[must_use]
pub fn string() -> Self {
Self::new("String")
.description("The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.")
.serialize(|value| match value {
Value::String(value) => Ok(Value::String(value.clone())),
_ => Err(format!("String cannot represent a value of type {}", value.kind())),
})
.parse_value(|value| match value {
Value::String(value) => Ok(Value::String(value.clone())),
_ => Err(format!("String cannot represent a value of type {}", value.kind())),
})
.parse_literal(|value| match value {
ast::Value::String(value) => Ok(Value::String(Arc::from(value.as_ref()))),
_ => Err("String cannot represent a non-string literal".into()),
})
.builtin()
}
#[must_use]
pub fn int() -> Self {
Self::new("Int")
.description("The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.")
.serialize(|value| match value {
Value::Int(value) => Ok(Value::Int(*value)),
Value::BigInt(value) => i32::try_from(**value)
.map(Value::Int)
.map_err(|_| "Int cannot represent non 32-bit signed integer value".into()),
_ => Err(format!("Int cannot represent a value of type {}", value.kind())),
})
.parse_value(|value| match value {
Value::Int(value) => Ok(Value::Int(*value)),
Value::BigInt(value) => i32::try_from(**value)
.map(Value::Int)
.map_err(|_| "Int cannot represent non 32-bit signed integer value".into()),
_ => Err(format!("Int cannot represent a value of type {}", value.kind())),
})
.parse_literal(|value| match value {
ast::Value::Int(value) => i32::try_from(*value)
.map(Value::Int)
.map_err(|_| "Int cannot represent non 32-bit signed integer value".into()),
_ => Err("Int cannot represent a non-integer literal".into()),
})
.builtin()
}
#[must_use]
pub fn float() -> Self {
Self::new("Float")
.description("The `Float` scalar type represents signed double-precision fractional values as specified by IEEE 754.")
.serialize(|value| match value {
Value::Float(value) if value.is_finite() => Ok(Value::Float(*value)),
Value::Int(value) => Ok(Value::Float(f64::from(*value))),
Value::BigInt(value) => Ok(Value::Float(**value as f64)),
Value::Float(_) => Err("Float cannot represent a non-finite value".into()),
_ => Err(format!("Float cannot represent a value of type {}", value.kind())),
})
.parse_value(|value| match value {
Value::Float(value) if value.is_finite() => Ok(Value::Float(*value)),
Value::Int(value) => Ok(Value::Float(f64::from(*value))),
Value::BigInt(value) => Ok(Value::Float(**value as f64)),
Value::Float(_) => Err("Float cannot represent a non-finite value".into()),
_ => Err(format!("Float cannot represent a value of type {}", value.kind())),
})
.parse_literal(|value| match value {
ast::Value::Float(value) if value.is_finite() => Ok(Value::Float(*value)),
ast::Value::Float(_) => Err("Float cannot represent a non-finite value".into()),
ast::Value::Int(value) => Ok(Value::Float(*value as f64)),
_ => Err("Float cannot represent a non-numeric literal".into()),
})
.builtin()
}
#[must_use]
pub fn boolean() -> Self {
Self::new("Boolean")
.description("The `Boolean` scalar type represents `true` or `false`.")
.serialize(|value| match value {
Value::Boolean(value) => Ok(Value::Boolean(*value)),
_ => Err(format!(
"Boolean cannot represent a value of type {}",
value.kind()
)),
})
.parse_value(|value| match value {
Value::Boolean(value) => Ok(Value::Boolean(*value)),
_ => Err(format!(
"Boolean cannot represent a value of type {}",
value.kind()
)),
})
.parse_literal(|value| match value {
ast::Value::Boolean(value) => Ok(Value::Boolean(*value)),
_ => Err("Boolean cannot represent a non-boolean literal".into()),
})
.builtin()
}
#[must_use]
pub fn id() -> Self {
Self::new("ID")
.description("The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `\"4\"`) or integer (such as `4`) input value will be accepted as an ID.")
.serialize(|value| match value {
Value::String(value) | Value::Enum(value) => Ok(Value::String(value.clone())),
Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
Value::BigInt(value) => Ok(Value::String(Arc::from(value.to_string()))),
_ => Err(format!("ID cannot represent a value of type {}", value.kind())),
})
.parse_value(|value| match value {
Value::String(value) | Value::Enum(value) => Ok(Value::String(value.clone())),
Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
Value::BigInt(value) => Ok(Value::String(Arc::from(value.to_string()))),
_ => Err(format!("ID cannot represent a value of type {}", value.kind())),
})
.parse_literal(|value| match value {
ast::Value::String(value) => Ok(Value::String(Arc::from(value.as_ref()))),
ast::Value::Int(value) => Ok(Value::String(Arc::from(value.to_string()))),
_ => Err("ID cannot represent a non-string and non-integer literal".into()),
})
.builtin()
}
#[must_use]
pub fn serialize_fn(&self) -> Option<&ScalarSerializeFn> {
self.serialize.as_ref()
}
#[must_use]
pub fn parse_value_fn(&self) -> Option<&ScalarParseValueFn> {
self.parse_value.as_ref()
}
#[must_use]
pub fn parse_literal_fn(&self) -> Option<&ScalarParseLiteralFn> {
self.parse_literal.as_ref()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct EnumValue {
pub name: Name,
pub description: Option<Arc<str>>,
pub deprecation_reason: Option<Arc<str>>,
pub directives: Vec<AppliedDirective>,
}
impl EnumValue {
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
}
#[derive(Clone, Debug)]
pub struct EnumType {
pub name: Name,
pub description: Option<Arc<str>>,
pub values: IndexMap<Name, EnumValue>,
pub directives: Vec<AppliedDirective>,
pub(crate) duplicates: Vec<Name>,
}
impl EnumType {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
values: IndexMap::new(),
directives: Vec::new(),
duplicates: Vec::new(),
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn value(mut self, name: impl Into<Name>) -> Self {
let name = name.into();
if self.values.contains_key(&name) {
self.duplicates.push(name.clone());
}
self.values.insert(
name.clone(),
EnumValue {
name,
description: None,
deprecation_reason: None,
directives: Vec::new(),
},
);
self
}
#[must_use]
pub fn value_with(
mut self,
name: impl Into<Name>,
description: Option<Arc<str>>,
deprecation_reason: Option<Arc<str>>,
) -> Self {
let name = name.into();
if self.values.contains_key(&name) {
self.duplicates.push(name.clone());
}
self.values.insert(
name.clone(),
EnumValue {
name,
description,
deprecation_reason,
directives: Vec::new(),
},
);
self
}
#[must_use]
pub fn has_value(&self, name: &str) -> bool {
map_get(&self.values, name).is_some()
}
}
#[derive(Clone, Debug)]
pub struct InputValue {
pub name: Name,
pub description: Option<Arc<str>>,
pub ty: TypeRef,
pub default_value: Option<Value>,
pub deprecation_reason: Option<Arc<str>>,
pub directives: Vec<AppliedDirective>,
}
impl InputValue {
#[must_use]
pub fn new(name: impl Into<Name>, ty: TypeRef) -> Self {
Self {
name: name.into(),
description: None,
ty,
default_value: None,
deprecation_reason: None,
directives: Vec::new(),
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn default_value(mut self, value: impl Into<Value>) -> Self {
self.default_value = Some(value.into());
self
}
#[must_use]
pub fn deprecation_reason(mut self, reason: impl Into<Arc<str>>) -> Self {
self.deprecation_reason = Some(reason.into());
self
}
}
#[derive(Clone, Debug)]
pub struct InputObjectType {
pub name: Name,
pub description: Option<Arc<str>>,
pub fields: IndexMap<Name, InputValue>,
pub one_of: bool,
pub directives: Vec<AppliedDirective>,
pub(crate) duplicates: Vec<Name>,
}
impl InputObjectType {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
fields: IndexMap::new(),
one_of: false,
directives: Vec::new(),
duplicates: Vec::new(),
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn field(mut self, field: InputValue) -> Self {
if self.fields.contains_key(&field.name) {
self.duplicates.push(field.name.clone());
}
self.fields.insert(field.name.clone(), field);
self
}
pub fn insert_field(&mut self, field: InputValue) {
if self.fields.contains_key(&field.name) {
self.duplicates.push(field.name.clone());
}
self.fields.insert(field.name.clone(), field);
}
#[must_use]
pub fn one_of(mut self) -> Self {
self.one_of = true;
self
}
}
#[derive(Clone)]
pub struct Field {
pub name: Name,
pub description: Option<Arc<str>>,
pub args: IndexMap<Name, InputValue>,
pub ty: TypeRef,
pub deprecation_reason: Option<Arc<str>>,
pub directives: Vec<AppliedDirective>,
pub resolve: Option<ResolveFn>,
pub subscribe: Option<SubscribeFn>,
pub complexity: Option<ComplexityFn>,
pub(crate) duplicate_args: Vec<Name>,
pub(crate) type_index: Option<u32>,
}
impl fmt::Debug for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Field")
.field("name", &self.name)
.field("description", &self.description)
.field("args", &self.args)
.field("ty", &self.ty)
.field("deprecation_reason", &self.deprecation_reason)
.field("directives", &self.directives)
.field("resolve", &self.resolve.is_some())
.field("subscribe", &self.subscribe.is_some())
.finish()
}
}
impl Field {
#[must_use]
pub fn new(name: impl Into<Name>, ty: TypeRef) -> Self {
Self {
name: name.into(),
description: None,
args: IndexMap::new(),
ty,
deprecation_reason: None,
directives: Vec::new(),
resolve: None,
subscribe: None,
complexity: None,
duplicate_args: Vec::new(),
type_index: None,
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn arg(mut self, argument: InputValue) -> Self {
if self.args.contains_key(&argument.name) {
self.duplicate_args.push(argument.name.clone());
}
self.args.insert(argument.name.clone(), argument);
self
}
#[must_use]
pub fn deprecation_reason(mut self, reason: impl Into<Arc<str>>) -> Self {
self.deprecation_reason = Some(reason.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn resolve(
mut self,
resolve: impl for<'a> Fn(ResolverContext<'a>) -> ResolveFuture<'a> + Send + Sync + 'static,
) -> Self {
self.resolve = Some(Arc::new(resolve));
self
}
#[must_use]
pub fn subscribe(
mut self,
subscribe: impl for<'a> Fn(
ResolverContext<'a>,
) -> futures::future::BoxFuture<
'a,
Result<SubscriptionStream, GraphQLError>,
> + Send
+ Sync
+ 'static,
) -> Self {
self.subscribe = Some(Arc::new(subscribe));
self
}
#[must_use]
pub fn complexity(
mut self,
estimator: impl Fn(&crate::Object) -> u32 + Send + Sync + 'static,
) -> Self {
self.complexity = Some(Arc::new(estimator));
self
}
}
pub type ResolveFn =
Arc<dyn for<'a> Fn(ResolverContext<'a>) -> ResolveFuture<'a> + Send + Sync + 'static>;
pub type SubscribeFn = Arc<
dyn for<'a> Fn(
ResolverContext<'a>,
)
-> futures::future::BoxFuture<'a, Result<SubscriptionStream, GraphQLError>>
+ Send
+ Sync
+ 'static,
>;
pub type ComplexityFn = Arc<dyn Fn(&crate::Object) -> u32 + Send + Sync + 'static>;
#[derive(Debug)]
pub struct ResolveInfo<'a> {
pub field_name: &'a str,
pub parent_type: &'a str,
pub return_type: &'a TypeRef,
pub path: &'a [PathSegment],
pub schema: &'a Schema,
pub field_nodes: ast::FieldNodes<'a>,
pub operation: Option<&'a ast::OperationDefinition<'a>>,
pub fragments: &'a Fragments<'a>,
pub root_value: &'a Value,
pub variables: &'a crate::Object,
}
static EMPTY_ROOT_VALUE: Value = Value::Null;
static EMPTY_VARIABLES: std::sync::LazyLock<crate::Object> =
std::sync::LazyLock::new(crate::Object::new);
static EMPTY_FRAGMENTS: std::sync::LazyLock<Fragments<'static>> =
std::sync::LazyLock::new(Fragments::empty);
impl<'a> ResolveInfo<'a> {
#[must_use]
pub fn new(
field_name: &'a str,
parent_type: &'a str,
return_type: &'a TypeRef,
path: &'a [PathSegment],
schema: &'a Schema,
) -> Self {
Self {
field_name,
parent_type,
return_type,
path,
schema,
field_nodes: ast::FieldNodes::empty(),
operation: None,
fragments: &EMPTY_FRAGMENTS,
root_value: &EMPTY_ROOT_VALUE,
variables: &EMPTY_VARIABLES,
}
}
#[must_use]
pub fn with_field_nodes(mut self, field_nodes: ast::FieldNodes<'a>) -> Self {
self.field_nodes = field_nodes;
self
}
#[must_use]
pub fn with_operation(mut self, operation: &'a ast::OperationDefinition<'a>) -> Self {
self.operation = Some(operation);
self
}
#[must_use]
pub fn with_fragments(mut self, fragments: &'a Fragments<'a>) -> Self {
self.fragments = fragments;
self
}
#[must_use]
pub fn with_root_value(mut self, root_value: &'a Value) -> Self {
self.root_value = root_value;
self
}
#[must_use]
pub fn with_variables(mut self, variables: &'a crate::Object) -> Self {
self.variables = variables;
self
}
}
pub struct ResolverContext<'a> {
pub parent: &'a Value,
pub args: &'a crate::Object,
pub context: &'a ExecutionContext,
pub info: &'a ResolveInfo<'a>,
}
impl fmt::Debug for ResolverContext<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResolverContext")
.field("parent", &self.parent)
.field("args", &self.args)
.field("info", &self.info)
.finish_non_exhaustive()
}
}
pub type ResolveTypeFn =
Arc<dyn Fn(&Value, &ExecutionContext) -> Result<Name, GraphQLError> + Send + Sync + 'static>;
#[derive(Clone)]
pub struct ObjectType {
pub name: Name,
pub description: Option<Arc<str>>,
pub fields: IndexMap<Name, Field>,
pub interfaces: Vec<Name>,
pub directives: Vec<AppliedDirective>,
pub is_type_of: Option<Arc<dyn Fn(&Value) -> bool + Send + Sync>>,
pub(crate) duplicates: Vec<Name>,
}
impl fmt::Debug for ObjectType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ObjectType")
.field("name", &self.name)
.field("description", &self.description)
.field("fields", &self.fields)
.field("interfaces", &self.interfaces)
.field("directives", &self.directives)
.finish_non_exhaustive()
}
}
impl ObjectType {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
fields: IndexMap::new(),
interfaces: Vec::new(),
directives: Vec::new(),
is_type_of: None,
duplicates: Vec::new(),
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn field(mut self, field: Field) -> Self {
if self.fields.contains_key(&field.name) {
self.duplicates.push(field.name.clone());
}
self.fields.insert(field.name.clone(), field);
self
}
#[must_use]
pub fn implements(mut self, interface: impl Into<Name>) -> Self {
self.interfaces.push(interface.into());
self
}
#[must_use]
pub fn is_type_of(mut self, check: impl Fn(&Value) -> bool + Send + Sync + 'static) -> Self {
self.is_type_of = Some(Arc::new(check));
self
}
pub fn insert_field(&mut self, field: Field) {
if self.fields.contains_key(&field.name) {
self.duplicates.push(field.name.clone());
}
self.fields.insert(field.name.clone(), field);
}
#[must_use]
pub fn get_field(&self, name: &str) -> Option<&Field> {
map_get(&self.fields, name)
}
}
#[derive(Clone)]
pub struct InterfaceType {
pub name: Name,
pub description: Option<Arc<str>>,
pub fields: IndexMap<Name, Field>,
pub interfaces: Vec<Name>,
pub directives: Vec<AppliedDirective>,
pub resolve_type: Option<ResolveTypeFn>,
pub(crate) duplicates: Vec<Name>,
}
impl fmt::Debug for InterfaceType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InterfaceType")
.field("name", &self.name)
.field("description", &self.description)
.field("fields", &self.fields)
.field("interfaces", &self.interfaces)
.field("directives", &self.directives)
.finish_non_exhaustive()
}
}
impl InterfaceType {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
fields: IndexMap::new(),
interfaces: Vec::new(),
directives: Vec::new(),
resolve_type: None,
duplicates: Vec::new(),
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn field(mut self, field: Field) -> Self {
if self.fields.contains_key(&field.name) {
self.duplicates.push(field.name.clone());
}
self.fields.insert(field.name.clone(), field);
self
}
#[must_use]
pub fn implements(mut self, interface: impl Into<Name>) -> Self {
self.interfaces.push(interface.into());
self
}
pub fn insert_field(&mut self, field: Field) {
if self.fields.contains_key(&field.name) {
self.duplicates.push(field.name.clone());
}
self.fields.insert(field.name.clone(), field);
}
#[must_use]
pub fn resolve_type(
mut self,
resolve: impl Fn(&Value, &ExecutionContext) -> Result<Name, GraphQLError>
+ Send
+ Sync
+ 'static,
) -> Self {
self.resolve_type = Some(Arc::new(resolve));
self
}
#[must_use]
pub fn get_field(&self, name: &str) -> Option<&Field> {
map_get(&self.fields, name)
}
}
#[derive(Clone)]
pub struct UnionType {
pub name: Name,
pub description: Option<Arc<str>>,
pub types: Vec<Name>,
pub directives: Vec<AppliedDirective>,
pub resolve_type: Option<ResolveTypeFn>,
}
impl fmt::Debug for UnionType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UnionType")
.field("name", &self.name)
.field("description", &self.description)
.field("types", &self.types)
.field("directives", &self.directives)
.finish_non_exhaustive()
}
}
impl UnionType {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
types: Vec::new(),
directives: Vec::new(),
resolve_type: None,
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn member(mut self, ty: impl Into<Name>) -> Self {
self.types.push(ty.into());
self
}
#[must_use]
pub fn resolve_type(
mut self,
resolve: impl Fn(&Value, &ExecutionContext) -> Result<Name, GraphQLError>
+ Send
+ Sync
+ 'static,
) -> Self {
self.resolve_type = Some(Arc::new(resolve));
self
}
}
#[derive(Clone, Debug)]
pub enum Type {
Scalar(Arc<ScalarType>),
Object(Arc<ObjectType>),
Interface(Arc<InterfaceType>),
Union(Arc<UnionType>),
Enum(Arc<EnumType>),
InputObject(Arc<InputObjectType>),
}
impl Type {
#[must_use]
pub fn name(&self) -> &Name {
match self {
Self::Scalar(ty) => &ty.name,
Self::Object(ty) => &ty.name,
Self::Interface(ty) => &ty.name,
Self::Union(ty) => &ty.name,
Self::Enum(ty) => &ty.name,
Self::InputObject(ty) => &ty.name,
}
}
#[must_use]
pub const fn kind(&self) -> TypeKind {
match self {
Self::Scalar(_) => TypeKind::Scalar,
Self::Object(_) => TypeKind::Object,
Self::Interface(_) => TypeKind::Interface,
Self::Union(_) => TypeKind::Union,
Self::Enum(_) => TypeKind::Enum,
Self::InputObject(_) => TypeKind::InputObject,
}
}
#[must_use]
pub const fn is_input_type(&self) -> bool {
matches!(self, Self::Scalar(_) | Self::Enum(_) | Self::InputObject(_))
}
#[must_use]
pub const fn is_output_type(&self) -> bool {
!matches!(self, Self::InputObject(_))
}
#[must_use]
pub const fn is_leaf(&self) -> bool {
matches!(self, Self::Scalar(_) | Self::Enum(_))
}
#[must_use]
pub const fn is_composite(&self) -> bool {
matches!(self, Self::Object(_) | Self::Interface(_) | Self::Union(_))
}
#[must_use]
pub fn as_scalar(&self) -> Option<&Arc<ScalarType>> {
match self {
Self::Scalar(ty) => Some(ty),
_ => None,
}
}
#[must_use]
pub fn as_object(&self) -> Option<&Arc<ObjectType>> {
match self {
Self::Object(ty) => Some(ty),
_ => None,
}
}
#[must_use]
pub fn as_interface(&self) -> Option<&Arc<InterfaceType>> {
match self {
Self::Interface(ty) => Some(ty),
_ => None,
}
}
#[must_use]
pub fn as_union(&self) -> Option<&Arc<UnionType>> {
match self {
Self::Union(ty) => Some(ty),
_ => None,
}
}
#[must_use]
pub fn as_enum(&self) -> Option<&Arc<EnumType>> {
match self {
Self::Enum(ty) => Some(ty),
_ => None,
}
}
#[must_use]
pub fn as_input_object(&self) -> Option<&Arc<InputObjectType>> {
match self {
Self::InputObject(ty) => Some(ty),
_ => None,
}
}
}
impl From<ScalarType> for Type {
fn from(value: ScalarType) -> Self {
Self::Scalar(Arc::new(value))
}
}
impl From<ObjectType> for Type {
fn from(value: ObjectType) -> Self {
Self::Object(Arc::new(value))
}
}
impl From<InterfaceType> for Type {
fn from(value: InterfaceType) -> Self {
Self::Interface(Arc::new(value))
}
}
impl From<UnionType> for Type {
fn from(value: UnionType) -> Self {
Self::Union(Arc::new(value))
}
}
impl From<EnumType> for Type {
fn from(value: EnumType) -> Self {
Self::Enum(Arc::new(value))
}
}
impl From<InputObjectType> for Type {
fn from(value: InputObjectType) -> Self {
Self::InputObject(Arc::new(value))
}
}
#[derive(Clone, Debug)]
pub struct DirectiveDefinition {
pub name: Name,
pub description: Option<Arc<str>>,
pub args: IndexMap<Name, InputValue>,
pub locations: Vec<ast::DirectiveLocation>,
pub repeatable: bool,
pub directives: Vec<AppliedDirective>,
pub deprecation_reason: Option<Arc<str>>,
pub(crate) duplicate_args: Vec<Name>,
}
impl DirectiveDefinition {
#[must_use]
pub fn new(name: impl Into<Name>) -> Self {
Self {
name: name.into(),
description: None,
args: IndexMap::new(),
locations: Vec::new(),
repeatable: false,
directives: Vec::new(),
deprecation_reason: None,
duplicate_args: Vec::new(),
}
}
#[must_use]
pub fn description(mut self, description: impl Into<Arc<str>>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn arg(mut self, argument: InputValue) -> Self {
if self.args.contains_key(&argument.name) {
self.duplicate_args.push(argument.name.clone());
}
self.args.insert(argument.name.clone(), argument);
self
}
#[must_use]
pub fn location(mut self, location: ast::DirectiveLocation) -> Self {
self.locations.push(location);
self
}
#[must_use]
pub fn repeatable(mut self) -> Self {
self.repeatable = true;
self
}
#[must_use]
pub fn directive(mut self, directive: AppliedDirective) -> Self {
self.directives.push(directive);
self
}
#[must_use]
pub fn deprecation_reason(mut self, reason: impl Into<Arc<str>>) -> Self {
self.deprecation_reason = Some(reason.into());
self
}
#[must_use]
pub fn skip() -> Self {
Self::new("skip")
.description("Directs the executor to skip this field or fragment when the `if` argument is true.")
.arg(
InputValue::new("if", TypeRef::boolean().non_null())
.description("Skipped when true."),
)
.location(ast::DirectiveLocation::Field)
.location(ast::DirectiveLocation::FragmentSpread)
.location(ast::DirectiveLocation::InlineFragment)
}
#[must_use]
pub fn include() -> Self {
Self::new("include")
.description("Directs the executor to include this field or fragment only when the `if` argument is true.")
.arg(
InputValue::new("if", TypeRef::boolean().non_null())
.description("Included when true."),
)
.location(ast::DirectiveLocation::Field)
.location(ast::DirectiveLocation::FragmentSpread)
.location(ast::DirectiveLocation::InlineFragment)
}
#[must_use]
pub fn deprecated() -> Self {
Self::new("deprecated")
.description("Marks an element of a GraphQL schema as no longer supported.")
.arg(
InputValue::new("reason", TypeRef::string())
.description("Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).")
.default_value("No longer supported"),
)
.location(ast::DirectiveLocation::FieldDefinition)
.location(ast::DirectiveLocation::ArgumentDefinition)
.location(ast::DirectiveLocation::InputFieldDefinition)
.location(ast::DirectiveLocation::EnumValue)
.location(ast::DirectiveLocation::DirectiveDefinition)
}
#[must_use]
pub fn specified_by() -> Self {
Self::new("specifiedBy")
.description("Exposes a URL that specifies the behavior of this scalar.")
.arg(
InputValue::new("url", TypeRef::string().non_null())
.description("The URL that specifies the behavior of this scalar."),
)
.location(ast::DirectiveLocation::Scalar)
}
#[must_use]
pub fn one_of() -> Self {
Self::new("oneOf")
.description(
"Indicates exactly one field must be supplied and this field must not be `null`.",
)
.location(ast::DirectiveLocation::InputObject)
}
}