Skip to main content

juniper/executor/
mod.rs

1//! Resolve the document to values
2
3use std::{
4    borrow::Cow,
5    cmp::Ordering,
6    collections::HashMap,
7    fmt::{Debug, Display},
8    mem,
9    pin::Pin,
10    sync::{Arc, RwLock},
11};
12
13use arcstr::ArcStr;
14use fnv::FnvHashMap;
15use futures::Stream;
16
17use crate::{
18    ast::{Fragment, FromInputValue, InputValue, Selection, ToInputValue, Type},
19    parser::SourcePosition,
20    schema::{
21        meta::{
22            Argument, DeprecationStatus, EnumMeta, EnumValue, Field, InputObjectMeta,
23            InterfaceMeta, ListMeta, MetaType, NullableMeta, ObjectMeta, PlaceholderMeta,
24            ScalarMeta, UnionMeta,
25        },
26        model::{SchemaType, TypeType},
27    },
28    types::{
29        async_await::GraphQLValueAsync,
30        base::{GraphQLType, GraphQLValue},
31        name::Name,
32        subscriptions::GraphQLSubscriptionValue,
33    },
34    value::{DefaultScalarValue, ParseScalarValue, ScalarValue, Value},
35};
36
37pub use self::{
38    look_ahead::{
39        Applies, LookAheadArgument, LookAheadChildren, LookAheadList, LookAheadObject,
40        LookAheadSelection, LookAheadValue,
41    },
42    owned_executor::OwnedExecutor,
43    validated_operation::ValidatedOperation,
44};
45
46mod look_ahead;
47mod owned_executor;
48mod validated_operation;
49
50#[expect(missing_docs, reason = "self-explanatory")]
51#[derive(Clone)]
52pub enum FieldPath<'a> {
53    Root(SourcePosition),
54    Field(&'a str, SourcePosition, Arc<FieldPath<'a>>),
55}
56
57/// Query execution engine
58///
59/// The executor helps drive the query execution in a schema. It keeps track
60/// of the current field stack, context, variables, and errors.
61pub struct Executor<'r, 'a, CtxT, S = DefaultScalarValue>
62where
63    CtxT: 'a,
64    S: 'a,
65{
66    fragments: &'r HashMap<&'a str, Fragment<'a, S>>,
67    variables: &'r Variables<S>,
68    current_selection_set: Option<&'r [Selection<'a, S>]>,
69    parent_selection_set: Option<&'r [Selection<'a, S>]>,
70    current_type: TypeType<'a, S>,
71    schema: &'a SchemaType<S>,
72    context: &'a CtxT,
73    errors: &'r RwLock<Vec<ExecutionError<S>>>,
74    field_path: Arc<FieldPath<'a>>,
75
76    /// Serial execution of the fields in the current selection set.
77    ///
78    /// The GraphQL specification requires serial execution of the root fields of a mutation.
79    /// Fragments at the root keep the flag. Field sub-executors clear the flag because the fields
80    /// of nested selection sets execute normally.
81    ///
82    /// See <https://spec.graphql.org/September2025#sec-Normal-and-Serial-Execution>.
83    serial: bool,
84}
85
86/// Error type for errors that occur during query execution
87///
88/// All execution errors contain the source position in the query of the field
89/// that failed to resolve. It also contains the field stack.
90#[derive(Clone, Debug, PartialEq)]
91pub struct ExecutionError<S> {
92    location: SourcePosition,
93    path: Vec<String>,
94    error: FieldError<S>,
95}
96
97impl<S> Eq for ExecutionError<S> where Self: PartialEq {}
98
99impl<S> ExecutionError<S> {
100    /// Constructs a new [`ExecutionError`] occurring at the beginning of the query.
101    pub fn at_origin(error: FieldError<S>) -> ExecutionError<S> {
102        ExecutionError {
103            location: SourcePosition::new_origin(),
104            path: Vec::new(),
105            error,
106        }
107    }
108}
109
110impl<S> PartialOrd for ExecutionError<S>
111where
112    Self: PartialEq,
113{
114    fn partial_cmp(&self, other: &ExecutionError<S>) -> Option<Ordering> {
115        Some(self.cmp(other))
116    }
117}
118
119impl<S> Ord for ExecutionError<S>
120where
121    Self: Eq,
122{
123    fn cmp(&self, other: &ExecutionError<S>) -> Ordering {
124        (&self.location, &self.path, &self.error.message).cmp(&(
125            &other.location,
126            &other.path,
127            &other.error.message,
128        ))
129    }
130}
131
132/// Error type for errors that occur during field resolution
133///
134/// Field errors are represented by a human-readable error message and an
135/// optional `Value` structure containing additional information.
136///
137/// They can be converted to from any type that implements `std::fmt::Display`,
138/// which makes error chaining with the `?` operator a breeze:
139///
140/// ```rust
141/// # use juniper::{FieldError, ScalarValue};
142/// fn get_string(data: Vec<u8>) -> Result<String, FieldError>
143/// {
144///     let s = String::from_utf8(data)?;
145///     Ok(s)
146/// }
147/// ```
148#[derive(Clone, Debug, PartialEq)]
149pub struct FieldError<S = DefaultScalarValue> {
150    message: String,
151    extensions: Value<S>,
152}
153
154impl<T: Display, S> From<T> for FieldError<S> {
155    fn from(e: T) -> Self {
156        Self {
157            message: e.to_string(),
158            extensions: Value::Null,
159        }
160    }
161}
162
163impl<S> FieldError<S> {
164    /// Construct a new [`FieldError`] with additional data.
165    ///
166    /// You can use the [`graphql_value!`] macro for construction:
167    /// ```rust
168    /// use juniper::{graphql_value, FieldError};
169    ///
170    /// # let _: FieldError =
171    /// FieldError::new(
172    ///     "Could not open connection to the database",
173    ///     graphql_value!({"internal_error": "Connection refused"}),
174    /// );
175    /// ```
176    ///
177    /// The `extensions` parameter will be added to the `"extensions"` field of
178    /// the `"errors"` object in response:
179    /// ```json
180    /// {
181    ///   "errors": [
182    ///     "message": "Could not open connection to the database",
183    ///     "locations": [{"line": 2, "column": 4}],
184    ///     "extensions": {
185    ///       "internal_error": "Connection refused"
186    ///     }
187    ///   ]
188    /// }
189    /// ```
190    ///
191    /// If the argument is [`Value::Null`], then no extra data will be included.
192    ///
193    /// [`graphql_value!`]: macro@crate::graphql_value
194    #[must_use]
195    pub fn new<T: Display>(e: T, extensions: Value<S>) -> Self {
196        Self {
197            message: e.to_string(),
198            extensions,
199        }
200    }
201
202    /// Returns `"message"` field of this [`FieldError`].
203    #[must_use]
204    pub fn message(&self) -> &str {
205        &self.message
206    }
207
208    /// Returns `"extensions"` field of this [`FieldError`].
209    ///
210    /// If there is no `"extensions"`, then [`Value::Null`] will be returned.
211    #[must_use]
212    pub fn extensions(&self) -> &Value<S> {
213        &self.extensions
214    }
215
216    /// Maps the [`ScalarValue`] type of this [`FieldError`] into the specified
217    /// one.
218    #[must_use]
219    pub fn map_scalar_value<T>(self) -> FieldError<T>
220    where
221        S: ScalarValue,
222        T: ScalarValue,
223    {
224        FieldError {
225            message: self.message,
226            extensions: self.extensions.map_scalar_value(),
227        }
228    }
229
230    /// Maps the [`FieldError::message`] with the given function.
231    #[must_use]
232    pub fn map_message(self, f: impl FnOnce(String) -> String) -> Self {
233        Self {
234            message: f(self.message),
235            extensions: self.extensions,
236        }
237    }
238}
239
240/// [`Result`] of resolving the value of a field of type `T`.
241pub type FieldResult<T, S = DefaultScalarValue> = Result<T, FieldError<S>>;
242
243/// [`Result`] of resolving an unspecified field.
244pub type ExecutionResult<S = DefaultScalarValue> = Result<Value<S>, FieldError<S>>;
245
246/// [`Box`]ed [`Stream`] yielding `Result<Value<S>, Vec<ExecutionError<S>>>`.
247pub type ValuesStream<'a, S = DefaultScalarValue> =
248    Pin<Box<dyn Stream<Item = Result<Value<S>, Vec<ExecutionError<S>>>> + Send + 'a>>;
249
250/// [`HashMap`] of variables used for substitution during query execution.
251pub type Variables<S = DefaultScalarValue> = HashMap<String, InputValue<S>>;
252
253/// Custom error handling trait to enable error types other than [`FieldError`]
254/// to be specified as return value.
255///
256/// Any custom error type should implement this trait to convert itself into a
257/// [`FieldError`].
258pub trait IntoFieldError<S = DefaultScalarValue> {
259    /// Performs the custom conversion into a [`FieldError`].
260    #[must_use]
261    fn into_field_error(self) -> FieldError<S>;
262}
263
264impl<S1: ScalarValue, S2: ScalarValue> IntoFieldError<S2> for FieldError<S1> {
265    fn into_field_error(self) -> FieldError<S2> {
266        self.map_scalar_value()
267    }
268}
269
270impl<S> IntoFieldError<S> for std::convert::Infallible {
271    fn into_field_error(self) -> FieldError<S> {
272        match self {}
273    }
274}
275
276impl<S> IntoFieldError<S> for &str {
277    fn into_field_error(self) -> FieldError<S> {
278        FieldError::<S>::from(self)
279    }
280}
281
282impl<S> IntoFieldError<S> for String {
283    fn into_field_error(self) -> FieldError<S> {
284        FieldError::<S>::from(self)
285    }
286}
287
288impl<S> IntoFieldError<S> for Cow<'_, str> {
289    fn into_field_error(self) -> FieldError<S> {
290        FieldError::<S>::from(self)
291    }
292}
293
294impl<S> IntoFieldError<S> for Box<str> {
295    fn into_field_error(self) -> FieldError<S> {
296        FieldError::<S>::from(self)
297    }
298}
299
300#[doc(hidden)]
301pub trait IntoResolvable<'a, S, T, C>
302where
303    T: GraphQLValue<S>,
304    S: ScalarValue,
305{
306    type Type;
307
308    #[doc(hidden)]
309    fn into_resolvable(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S>;
310}
311
312impl<'a, S, T, C> IntoResolvable<'a, S, T, C> for T
313where
314    T: GraphQLValue<S>,
315    S: ScalarValue,
316    T::Context: FromContext<C>,
317{
318    type Type = T;
319
320    fn into_resolvable(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> {
321        Ok(Some((FromContext::from(ctx), self)))
322    }
323}
324
325impl<'a, S, T, C, E: IntoFieldError<S>> IntoResolvable<'a, S, T, C> for Result<T, E>
326where
327    S: ScalarValue,
328    T: GraphQLValue<S>,
329    T::Context: FromContext<C>,
330{
331    type Type = T;
332
333    fn into_resolvable(self, ctx: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> {
334        self.map(|v: T| Some((<T::Context as FromContext<C>>::from(ctx), v)))
335            .map_err(IntoFieldError::into_field_error)
336    }
337}
338
339impl<'a, S, T, C> IntoResolvable<'a, S, T, C> for (&'a T::Context, T)
340where
341    S: ScalarValue,
342    T: GraphQLValue<S>,
343{
344    type Type = T;
345
346    fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S> {
347        Ok(Some(self))
348    }
349}
350
351impl<'a, S, T, C> IntoResolvable<'a, S, Option<T>, C> for Option<(&'a T::Context, T)>
352where
353    S: ScalarValue,
354    T: GraphQLValue<S>,
355{
356    type Type = T;
357
358    fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, Option<T>)>, S> {
359        Ok(self.map(|(ctx, v)| (ctx, Some(v))))
360    }
361}
362
363impl<'a, S1, S2, T, C> IntoResolvable<'a, S2, T, C> for FieldResult<(&'a T::Context, T), S1>
364where
365    S1: ScalarValue,
366    S2: ScalarValue,
367    T: GraphQLValue<S2>,
368{
369    type Type = T;
370
371    fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, T)>, S2> {
372        self.map(Some).map_err(FieldError::map_scalar_value)
373    }
374}
375
376impl<'a, S1, S2, T, C> IntoResolvable<'a, S2, Option<T>, C>
377    for FieldResult<Option<(&'a T::Context, T)>, S1>
378where
379    S1: ScalarValue,
380    S2: ScalarValue,
381    T: GraphQLValue<S2>,
382{
383    type Type = T;
384
385    fn into_resolvable(self, _: &'a C) -> FieldResult<Option<(&'a T::Context, Option<T>)>, S2> {
386        self.map(|o| o.map(|(ctx, v)| (ctx, Some(v))))
387            .map_err(FieldError::map_scalar_value)
388    }
389}
390
391/// Conversion trait for context types
392///
393/// Used to support different context types for different parts of an
394/// application. By making each `GraphQL` type only aware of as much
395/// context as it needs to, isolation and robustness can be
396/// improved. Implement this trait if you have contexts that can
397/// generally be converted between each other.
398///
399/// The empty tuple `()` can be converted into from any context type,
400/// making it suitable for `GraphQL` that don't need _any_ context to
401/// work, e.g. scalars or enums.
402pub trait FromContext<T> {
403    /// Perform the conversion
404    fn from(value: &T) -> &Self;
405}
406
407/// Marker trait for types that can act as context objects for `GraphQL` types.
408pub trait Context {}
409
410impl<C: Context> Context for &C {}
411
412static NULL_CONTEXT: () = ();
413
414impl<T> FromContext<T> for () {
415    fn from(_: &T) -> &Self {
416        &NULL_CONTEXT
417    }
418}
419
420impl<T> FromContext<T> for T
421where
422    T: Context,
423{
424    fn from(value: &T) -> &Self {
425        value
426    }
427}
428
429impl<'r, 'a, CtxT, S> Executor<'r, 'a, CtxT, S>
430where
431    S: ScalarValue,
432{
433    /// Resolve a single arbitrary value into a stream of [`Value`]s.
434    /// If a field fails to resolve, pushes error to `Executor`
435    /// and returns `Value::Null`.
436    pub async fn resolve_into_stream<'i, 'v, 'res, T>(
437        &'r self,
438        info: &'i T::TypeInfo,
439        value: &'v T,
440    ) -> Value<ValuesStream<'res, S>>
441    where
442        'i: 'res,
443        'v: 'res,
444        'a: 'res,
445        T: GraphQLSubscriptionValue<S, Context = CtxT> + ?Sized,
446        T::TypeInfo: Sync,
447        CtxT: Sync,
448        S: Send + Sync,
449    {
450        self.subscribe(info, value).await.unwrap_or_else(|e| {
451            self.push_error(e);
452            Value::Null
453        })
454    }
455
456    /// Resolve a single arbitrary value into a stream of [`Value`]s.
457    /// Calls `resolve_into_stream` on `T`.
458    pub async fn subscribe<'s, 't, 'res, T>(
459        &'r self,
460        info: &'t T::TypeInfo,
461        value: &'t T,
462    ) -> Result<Value<ValuesStream<'res, S>>, FieldError<S>>
463    where
464        't: 'res,
465        'a: 'res,
466        T: GraphQLSubscriptionValue<S, Context = CtxT> + ?Sized,
467        T::TypeInfo: Sync,
468        CtxT: Sync,
469        S: Send + Sync,
470    {
471        value.resolve_into_stream(info, self).await
472    }
473
474    /// Resolve a single arbitrary value, mapping the context to a new type
475    pub fn resolve_with_ctx<NewCtxT, T>(&self, info: &T::TypeInfo, value: &T) -> ExecutionResult<S>
476    where
477        NewCtxT: FromContext<CtxT>,
478        T: GraphQLValue<S, Context = NewCtxT> + ?Sized,
479    {
480        self.replaced_context(<NewCtxT as FromContext<CtxT>>::from(self.context))
481            .resolve(info, value)
482    }
483
484    /// Resolve a single arbitrary value into an `ExecutionResult`
485    pub fn resolve<T>(&self, info: &T::TypeInfo, value: &T) -> ExecutionResult<S>
486    where
487        T: GraphQLValue<S, Context = CtxT> + ?Sized,
488    {
489        value.resolve(info, self.current_selection_set, self)
490    }
491
492    /// Resolve a single arbitrary value into an `ExecutionResult`
493    pub async fn resolve_async<T>(&self, info: &T::TypeInfo, value: &T) -> ExecutionResult<S>
494    where
495        T: GraphQLValueAsync<S, Context = CtxT> + ?Sized,
496        T::TypeInfo: Sync,
497        CtxT: Sync,
498        S: Send + Sync,
499    {
500        value
501            .resolve_async(info, self.current_selection_set, self)
502            .await
503    }
504
505    /// Resolve a single arbitrary value, mapping the context to a new type
506    pub async fn resolve_with_ctx_async<NewCtxT, T>(
507        &self,
508        info: &T::TypeInfo,
509        value: &T,
510    ) -> ExecutionResult<S>
511    where
512        T: GraphQLValueAsync<S, Context = NewCtxT> + ?Sized,
513        T::TypeInfo: Sync,
514        NewCtxT: FromContext<CtxT> + Sync,
515        S: Send + Sync,
516    {
517        let e = self.replaced_context(<NewCtxT as FromContext<CtxT>>::from(self.context));
518        e.resolve_async(info, value).await
519    }
520
521    /// Resolve a single arbitrary value into a return value
522    ///
523    /// If the field fails to resolve, `null` will be returned.
524    pub fn resolve_into_value<T>(&self, info: &T::TypeInfo, value: &T) -> Value<S>
525    where
526        T: GraphQLValue<S, Context = CtxT>,
527    {
528        self.resolve(info, value).unwrap_or_else(|e| {
529            self.push_error(e);
530            Value::null()
531        })
532    }
533
534    /// Resolve a single arbitrary value into a return value
535    ///
536    /// If the field fails to resolve, `null` will be returned.
537    pub async fn resolve_into_value_async<T>(&self, info: &T::TypeInfo, value: &T) -> Value<S>
538    where
539        T: GraphQLValueAsync<S, Context = CtxT> + ?Sized,
540        T::TypeInfo: Sync,
541        CtxT: Sync,
542        S: Send + Sync,
543    {
544        self.resolve_async(info, value).await.unwrap_or_else(|e| {
545            self.push_error(e);
546            Value::null()
547        })
548    }
549
550    /// Derive a new executor by replacing the context
551    ///
552    /// This can be used to connect different types, e.g. from different Rust
553    /// libraries, that require different context types.
554    pub fn replaced_context<'b, NewCtxT>(
555        &'b self,
556        ctx: &'b NewCtxT,
557    ) -> Executor<'b, 'b, NewCtxT, S> {
558        Executor {
559            fragments: self.fragments,
560            variables: self.variables,
561            current_selection_set: self.current_selection_set,
562            parent_selection_set: self.parent_selection_set,
563            current_type: self.current_type.clone(),
564            schema: self.schema,
565            context: ctx,
566            errors: self.errors,
567            field_path: self.field_path.clone(),
568            serial: self.serial,
569        }
570    }
571
572    #[doc(hidden)]
573    pub fn field_sub_executor<'s>(
574        &'s self,
575        field_alias: &'a str,
576        field_name: &'s str,
577        location: SourcePosition,
578        selection_set: Option<&'s [Selection<'a, S>]>,
579    ) -> Executor<'s, 'a, CtxT, S> {
580        Executor {
581            fragments: self.fragments,
582            variables: self.variables,
583            current_selection_set: selection_set,
584            parent_selection_set: self.current_selection_set,
585            current_type: self.schema.make_type(
586                &self
587                    .current_type
588                    .innermost_concrete()
589                    .field_by_name(field_name)
590                    .expect("Field not found on inner type")
591                    .field_type,
592            ),
593            schema: self.schema,
594            context: self.context,
595            errors: self.errors,
596            field_path: Arc::new(FieldPath::Field(
597                field_alias,
598                location,
599                Arc::clone(&self.field_path),
600            )),
601            serial: false,
602        }
603    }
604
605    #[doc(hidden)]
606    pub fn type_sub_executor<'s>(
607        &'s self,
608        type_name: Option<&'s str>,
609        selection_set: Option<&'s [Selection<'a, S>]>,
610    ) -> Executor<'s, 'a, CtxT, S> {
611        Executor {
612            fragments: self.fragments,
613            variables: self.variables,
614            current_selection_set: selection_set,
615            parent_selection_set: self.current_selection_set,
616            current_type: match type_name {
617                Some(type_name) => self.schema.type_by_name(type_name).expect("Type not found"),
618                None => self.current_type.clone(),
619            },
620            schema: self.schema,
621            context: self.context,
622            errors: self.errors,
623            field_path: self.field_path.clone(),
624            serial: self.serial,
625        }
626    }
627
628    /// `Executor`'s current selection set
629    pub(crate) fn current_selection_set(&self) -> Option<&[Selection<'a, S>]> {
630        self.current_selection_set
631    }
632
633    /// Returns `true` if the fields of the current selection set execute serially.
634    pub(crate) fn is_serial(&self) -> bool {
635        self.serial
636    }
637
638    /// Access the current context
639    ///
640    /// You usually provide the context when calling the top-level `execute`
641    /// function, or using the context factory.
642    pub fn context(&self) -> &'r CtxT {
643        self.context
644    }
645
646    /// The currently executing schema
647    pub fn schema(&self) -> &'a SchemaType<S> {
648        self.schema
649    }
650
651    #[doc(hidden)]
652    pub fn current_type(&self) -> &TypeType<'a, S> {
653        &self.current_type
654    }
655
656    #[doc(hidden)]
657    pub fn variables(&self) -> &'r Variables<S> {
658        self.variables
659    }
660
661    #[doc(hidden)]
662    pub fn fragment_by_name<'s>(&'s self, name: &str) -> Option<&'s Fragment<'a, S>> {
663        self.fragments.get(name)
664    }
665
666    /// The current location of the executor
667    pub fn location(&self) -> &SourcePosition {
668        self.field_path.location()
669    }
670
671    /// Add an error to the execution engine at the current executor location
672    pub fn push_error(&self, error: FieldError<S>) {
673        self.push_error_at(error, *self.location());
674    }
675
676    /// Add an error to the execution engine at a specific location
677    pub fn push_error_at(&self, error: FieldError<S>, location: SourcePosition) {
678        let mut path = Vec::new();
679        self.field_path.construct_path(&mut path);
680
681        let mut errors = self.errors.write().unwrap();
682
683        errors.push(ExecutionError {
684            location,
685            path,
686            error,
687        });
688    }
689
690    /// Pushes an error at `location` for a `null` result of the non-null `field_name` field of the
691    /// `parent_type`.
692    ///
693    /// Pushes nothing if an error exists at or below the current path. The `null` result then
694    /// comes from that error. The GraphQL specification allows only one error per field.
695    pub(crate) fn push_non_null_violation_at(
696        &self,
697        parent_type: &MetaType<S>,
698        field_name: &str,
699        location: SourcePosition,
700    ) {
701        let mut path = Vec::new();
702        self.field_path.construct_path(&mut path);
703
704        let mut errors = self.errors.write().unwrap();
705        if errors.iter().any(|e| e.path.starts_with(&path)) {
706            return;
707        }
708
709        let type_name = parent_type.name().map_or("<unknown>", AsRef::as_ref);
710        errors.push(ExecutionError {
711            location,
712            path,
713            error: format!("Cannot return null for non-nullable field {type_name}.{field_name}.")
714                .into(),
715        });
716    }
717
718    /// Returns new [`ExecutionError`] at current location
719    pub fn new_error(&self, error: FieldError<S>) -> ExecutionError<S> {
720        let mut path = Vec::new();
721        self.field_path.construct_path(&mut path);
722
723        ExecutionError {
724            location: *self.location(),
725            path,
726            error,
727        }
728    }
729
730    /// Takes errors from this [`Executor`] clearing its internal [`ExecutionError`]s buffer.
731    #[must_use]
732    pub fn take_errors(&self) -> Vec<ExecutionError<S>> {
733        mem::take(&mut self.errors.write().unwrap())
734    }
735
736    /// Construct a lookahead selection for the current selection.
737    ///
738    /// This allows seeing the whole selection and perform operations
739    /// affecting the children.
740    pub fn look_ahead(&'a self) -> LookAheadSelection<'a, S> {
741        let field_name = match *self.field_path {
742            FieldPath::Field(x, ..) => x,
743            FieldPath::Root(_) => unreachable!(),
744        };
745        self.parent_selection_set
746            .and_then(|p| {
747                // Search the parent's fields to find this field within the selection set.
748                p.iter().find_map(|x| {
749                    match x {
750                        Selection::Field(field) => {
751                            let field = &field.item;
752                            // TODO: support excludes.
753                            let name = field.name.item;
754                            let alias = field.alias.as_ref().map(|a| a.item);
755
756                            (alias.unwrap_or(name) == field_name).then(|| {
757                                LookAheadSelection::new(
758                                    look_ahead::SelectionSource::Field(field),
759                                    self.variables,
760                                    self.fragments,
761                                )
762                            })
763                        }
764                        Selection::FragmentSpread(_) | Selection::InlineFragment(_) => None,
765                    }
766                })
767            })
768            .unwrap_or_else(|| {
769                // We didn't find this field in the parent's selection matching it, which means
770                // we're inside a `FragmentSpread`.
771                LookAheadSelection::new(
772                    look_ahead::SelectionSource::Spread {
773                        field_name,
774                        set: self.current_selection_set,
775                    },
776                    self.variables,
777                    self.fragments,
778                )
779            })
780    }
781
782    /// Create new `OwnedExecutor` and clone all current data
783    /// (except for errors) there
784    ///
785    /// New empty vector is created for `errors` because
786    /// existing errors won't be needed to be accessed by user
787    /// in OwnedExecutor as existing errors will be returned in
788    /// `execute_query`/`execute_mutation`/`resolve_into_stream`/etc.
789    pub fn as_owned_executor(&self) -> OwnedExecutor<'a, CtxT, S> {
790        OwnedExecutor {
791            fragments: self.fragments.clone(),
792            variables: self.variables.clone(),
793            current_selection_set: self.current_selection_set.map(|x| x.to_vec()),
794            parent_selection_set: self.parent_selection_set.map(|x| x.to_vec()),
795            current_type: self.current_type.clone(),
796            schema: self.schema,
797            context: self.context,
798            errors: RwLock::new(vec![]),
799            field_path: Arc::clone(&self.field_path),
800        }
801    }
802}
803
804impl FieldPath<'_> {
805    fn construct_path(&self, acc: &mut Vec<String>) {
806        match self {
807            FieldPath::Root(_) => (),
808            FieldPath::Field(name, _, parent) => {
809                parent.construct_path(acc);
810                acc.push((*name).into());
811            }
812        }
813    }
814
815    fn location(&self) -> &SourcePosition {
816        match *self {
817            FieldPath::Root(ref pos) | FieldPath::Field(_, ref pos, _) => pos,
818        }
819    }
820}
821
822impl<S> ExecutionError<S> {
823    #[doc(hidden)]
824    pub fn new(location: SourcePosition, path: &[&str], error: FieldError<S>) -> ExecutionError<S> {
825        ExecutionError {
826            location,
827            path: path.iter().map(|s| (*s).into()).collect(),
828            error,
829        }
830    }
831
832    /// The error message
833    pub fn error(&self) -> &FieldError<S> {
834        &self.error
835    }
836
837    /// The source location _in the query_ of the field that failed to resolve
838    pub fn location(&self) -> &SourcePosition {
839        &self.location
840    }
841
842    /// The path of fields leading to the field that generated this error
843    pub fn path(&self) -> &[String] {
844        &self.path
845    }
846}
847
848/// A type registry used to build schemas
849///
850/// The registry gathers metadata for all types in a schema. It provides
851/// convenience methods to convert types implementing the `GraphQLType` trait
852/// into `Type` instances and automatically registers them.
853pub struct Registry<S = DefaultScalarValue> {
854    /// Currently registered types
855    pub types: FnvHashMap<Name, MetaType<S>>,
856}
857
858impl<S> Registry<S> {
859    /// Constructs a new [`Registry`] out of the given `types`.
860    pub fn new(types: FnvHashMap<Name, MetaType<S>>) -> Self {
861        Self { types }
862    }
863
864    /// Returns a [`Type`] instance for the given [`GraphQLType`], registered in this [`Registry`].
865    ///
866    /// If this [`Registry`] hasn't seen a [`Type`] with such [`GraphQLType::name`] before, it will
867    /// construct the one and store it.
868    pub fn get_type<T>(&mut self, info: &T::TypeInfo) -> Type
869    where
870        T: GraphQLType<S> + ?Sized,
871        S: ScalarValue,
872    {
873        if let Some(name) = T::name(info) {
874            let validated_name = Name::new(name.clone()).unwrap();
875            if !self.types.contains_key(&name) {
876                self.insert_placeholder(
877                    validated_name.clone(),
878                    Type::nullable(name.clone()).wrap_non_null(),
879                );
880                let meta = T::meta(info, self);
881                self.types.insert(validated_name, meta);
882            }
883            self.types[&name].as_type()
884        } else {
885            T::meta(info, self).as_type()
886        }
887    }
888
889    /// Creates a [`Field`] with the provided `name`.
890    pub fn field<T>(&mut self, name: impl Into<ArcStr>, info: &T::TypeInfo) -> Field<S>
891    where
892        T: GraphQLType<S> + ?Sized,
893        S: ScalarValue,
894    {
895        Field {
896            name: name.into(),
897            description: None,
898            arguments: None,
899            field_type: self.get_type::<T>(info),
900            deprecation_status: DeprecationStatus::Current,
901        }
902    }
903
904    #[doc(hidden)]
905    pub fn field_convert<'a, T: IntoResolvable<'a, S, I, C>, I, C>(
906        &mut self,
907        name: impl Into<ArcStr>,
908        info: &I::TypeInfo,
909    ) -> Field<S>
910    where
911        I: GraphQLType<S>,
912        S: ScalarValue,
913    {
914        Field {
915            name: name.into(),
916            description: None,
917            arguments: None,
918            field_type: self.get_type::<I>(info),
919            deprecation_status: DeprecationStatus::Current,
920        }
921    }
922
923    /// Creates an [`Argument`] with the provided `name`.
924    pub fn arg<T>(&mut self, name: impl Into<ArcStr>, info: &T::TypeInfo) -> Argument<S>
925    where
926        T: GraphQLType<S> + FromInputValue<S>,
927        S: ScalarValue,
928    {
929        Argument::new(name, self.get_type::<T>(info))
930    }
931
932    /// Creates an [`Argument`] with the provided `name` and default `value`.
933    pub fn arg_with_default<T>(
934        &mut self,
935        name: impl Into<ArcStr>,
936        value: &T,
937        info: &T::TypeInfo,
938    ) -> Argument<S>
939    where
940        T: GraphQLType<S> + ToInputValue<S> + FromInputValue<S>,
941        S: ScalarValue,
942    {
943        self.arg::<T>(name, info)
944            .default_value(value.to_input_value())
945    }
946
947    fn insert_placeholder(&mut self, name: Name, of_type: Type) {
948        self.types
949            .entry(name)
950            .or_insert(MetaType::Placeholder(PlaceholderMeta { of_type }));
951    }
952
953    /// Creates a [`ScalarMeta`] type.
954    pub fn build_scalar_type<T>(&mut self, info: &T::TypeInfo) -> ScalarMeta<S>
955    where
956        T: GraphQLType<S> + FromInputValue<S> + ParseScalarValue<S>,
957        T::Error: IntoFieldError<S>,
958        S: ScalarValue,
959    {
960        let name = T::name(info).expect("Scalar types must be named. Implement `name()`");
961
962        ScalarMeta::new::<T>(name)
963    }
964
965    /// Creates a [`ListMeta`] type.
966    ///
967    /// Specifying `expected_size` will be used to ensure that values of this
968    /// type will always match it.
969    pub fn build_list_type<T>(
970        &mut self,
971        info: &T::TypeInfo,
972        expected_size: Option<usize>,
973    ) -> ListMeta
974    where
975        T: GraphQLType<S> + ?Sized,
976        S: ScalarValue,
977    {
978        let of_type = self.get_type::<T>(info);
979        ListMeta::new(of_type, expected_size)
980    }
981
982    /// Creates a [`NullableMeta`] type.
983    pub fn build_nullable_type<T>(&mut self, info: &T::TypeInfo) -> NullableMeta
984    where
985        T: GraphQLType<S> + ?Sized,
986        S: ScalarValue,
987    {
988        let of_type = self.get_type::<T>(info);
989        NullableMeta::new(of_type)
990    }
991
992    /// Creates an [`ObjectMeta`] type with the given `fields`.
993    pub fn build_object_type<T>(&mut self, info: &T::TypeInfo, fields: &[Field<S>]) -> ObjectMeta<S>
994    where
995        T: GraphQLType<S> + ?Sized,
996        S: ScalarValue,
997    {
998        let name = T::name(info).expect("Object types must be named. Implement name()");
999
1000        let mut v = fields.to_vec();
1001        v.push(self.field::<String>(arcstr::literal!("__typename"), &()));
1002        ObjectMeta::new(name, &v)
1003    }
1004
1005    /// Creates an [`EnumMeta`] type out of the provided `values`.
1006    pub fn build_enum_type<T>(&mut self, info: &T::TypeInfo, values: &[EnumValue]) -> EnumMeta<S>
1007    where
1008        T: GraphQLType<S> + FromInputValue<S>,
1009        T::Error: IntoFieldError<S>,
1010        S: ScalarValue,
1011    {
1012        let name = T::name(info).expect("Enum types must be named. Implement `name()`");
1013
1014        EnumMeta::new::<T>(name, values)
1015    }
1016
1017    /// Creates an [`InterfaceMeta`] type with the given `fields`.
1018    pub fn build_interface_type<T>(
1019        &mut self,
1020        info: &T::TypeInfo,
1021        fields: &[Field<S>],
1022    ) -> InterfaceMeta<S>
1023    where
1024        T: GraphQLType<S> + ?Sized,
1025        S: ScalarValue,
1026    {
1027        let name = T::name(info).expect("Interface types must be named. Implement name()");
1028
1029        let mut v = fields.to_vec();
1030        v.push(self.field::<String>(arcstr::literal!("__typename"), &()));
1031        InterfaceMeta::new(name, &v)
1032    }
1033
1034    /// Creates an [`UnionMeta`] type of the given `types`.
1035    pub fn build_union_type<T>(&mut self, info: &T::TypeInfo, types: &[Type]) -> UnionMeta
1036    where
1037        T: GraphQLType<S> + ?Sized,
1038        S: ScalarValue,
1039    {
1040        let name = T::name(info).expect("Union types must be named. Implement name()");
1041
1042        UnionMeta::new(name, types)
1043    }
1044
1045    /// Creates an [`InputObjectMeta`] type with the given `args`.
1046    pub fn build_input_object_type<T>(
1047        &mut self,
1048        info: &T::TypeInfo,
1049        args: &[Argument<S>],
1050    ) -> InputObjectMeta<S>
1051    where
1052        T: GraphQLType<S> + FromInputValue<S>,
1053        T::Error: IntoFieldError<S>,
1054        S: ScalarValue,
1055    {
1056        let name = T::name(info).expect("Input object types must be named. Implement name()");
1057
1058        InputObjectMeta::new::<T>(name, args)
1059    }
1060}